file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
./partial_match/1/0x5113A3Dd866A3EE8E973FC764cC380e6F07416Ef/sources/contracts/Forwarder.sol
@dev Minimal forwarder for GSNv2/
contract Forwarder is EIP712 { using ECDSA for bytes32; pragma solidity ^0.8.0; struct ForwardRequest { address from; address to; uint256 value; uint256 gas; uint256 nonce; bytes data; } bytes32 private constant TYPEHASH = keccak256("ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data)"); mapping(address => uint256) private _nonces; constructor() EIP712("GSNv2 Forwarder", "0.0.1") {} function getNonce(address from) public view returns (uint256) { return _nonces[from]; } function verify(ForwardRequest calldata req, bytes calldata signature) public view returns (bool) { address signer = _hashTypedDataV4( keccak256(abi.encode(TYPEHASH, req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data))) ).recover(signature); return _nonces[req.from] == req.nonce && signer == req.from; } function execute(ForwardRequest calldata req, bytes calldata signature) public payable returns (bool, bytes memory) { require(verify(req, signature), "MinimalForwarder: signature does not match request"); _nonces[req.from] = req.nonce + 1; abi.encodePacked(req.data, req.from) ); if (!success) { if (result.length < 68) revert("Transaction reverted silently"); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } return (success, result); } (bool success, bytes memory result) = req.to.call{ gas: req.gas, value: req.value }( function execute(ForwardRequest calldata req, bytes calldata signature) public payable returns (bool, bytes memory) { require(verify(req, signature), "MinimalForwarder: signature does not match request"); _nonces[req.from] = req.nonce + 1; abi.encodePacked(req.data, req.from) ); if (!success) { if (result.length < 68) revert("Transaction reverted silently"); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } return (success, result); } function execute(ForwardRequest calldata req, bytes calldata signature) public payable returns (bool, bytes memory) { require(verify(req, signature), "MinimalForwarder: signature does not match request"); _nonces[req.from] = req.nonce + 1; abi.encodePacked(req.data, req.from) ); if (!success) { if (result.length < 68) revert("Transaction reverted silently"); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } return (success, result); } assert(gasleft() > req.gas / 63); }
4,151,116
[ 1, 2930, 2840, 364, 20099, 364, 611, 13653, 90, 22, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2457, 20099, 353, 512, 2579, 27, 2138, 288, 203, 565, 1450, 7773, 19748, 364, 1731, 1578, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 1958, 17206, 691, 288, 203, 3639, 1758, 628, 31, 203, 3639, 1758, 358, 31, 203, 3639, 2254, 5034, 460, 31, 203, 3639, 2254, 5034, 16189, 31, 203, 3639, 2254, 5034, 7448, 31, 203, 3639, 1731, 501, 31, 203, 565, 289, 203, 203, 565, 1731, 1578, 3238, 5381, 3463, 15920, 273, 203, 3639, 417, 24410, 581, 5034, 2932, 8514, 691, 12, 2867, 628, 16, 2867, 358, 16, 11890, 5034, 460, 16, 11890, 5034, 16189, 16, 11890, 5034, 7448, 16, 3890, 501, 2225, 1769, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 5836, 764, 31, 203, 203, 203, 565, 3885, 1435, 512, 2579, 27, 2138, 2932, 43, 13653, 90, 22, 2457, 20099, 3113, 315, 20, 18, 20, 18, 21, 7923, 2618, 203, 565, 445, 336, 13611, 12, 2867, 628, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 5836, 764, 63, 2080, 15533, 203, 565, 289, 203, 203, 565, 445, 3929, 12, 8514, 691, 745, 892, 1111, 16, 1731, 745, 892, 3372, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 1758, 10363, 273, 389, 2816, 11985, 751, 58, 24, 12, 203, 5411, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 2399, 15920, 16, 1111, 18, 2080, 16, 1111, 18, 869, 16, 1111, 18, 1132, 16, 1111, 18, 31604, 16, 1111, 18, 12824, 2 ]
./full_match/1/0xdF3b985E15281EfecF203998200b26F024699F47/sources/browser/Brrr.sol
* @dev Returns the users deposit in alt coins and changes the circulating supply and treasury reserves based off the brrr sent back Emits withdraw event./
function _payBackBrrrCoins(uint256 _brrrAmount, address payable _owner, address _contract, uint256 _returnAmount) internal returns (bool){ require(_coin_deposits[_owner][_contract] >= _returnAmount, "More than deposit amount"); _balances[_owner] = _balances[_owner].sub(_brrrAmount); TreasuryReserve = TreasuryReserve.add(_brrrAmount); _totalSupply = TreasuryReserve; _circulatingSupply = _circulatingSupply.sub(_brrrAmount); emit Transfer(address(_owner), address(this), _brrrAmount); _coin_deposits[_owner][_contract] = _coin_deposits[_owner][_contract].sub(_returnAmount); _transferCoin(_owner, _contract, _returnAmount); emit Withdraw(address(_owner), _returnAmount); return true; }
8,441,537
[ 1, 1356, 326, 3677, 443, 1724, 316, 3770, 276, 9896, 471, 3478, 326, 5886, 1934, 1776, 14467, 471, 9787, 345, 22498, 400, 264, 3324, 2511, 3397, 326, 324, 523, 86, 3271, 1473, 7377, 1282, 598, 9446, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1377, 445, 389, 10239, 2711, 38, 523, 86, 39, 9896, 12, 11890, 5034, 389, 70, 523, 86, 6275, 16, 1758, 8843, 429, 389, 8443, 16, 1758, 389, 16351, 16, 2254, 5034, 389, 2463, 6275, 13, 2713, 1135, 261, 6430, 15329, 203, 3639, 2583, 24899, 12645, 67, 323, 917, 1282, 63, 67, 8443, 6362, 67, 16351, 65, 1545, 389, 2463, 6275, 16, 315, 7417, 2353, 443, 1724, 3844, 8863, 203, 3639, 389, 70, 26488, 63, 67, 8443, 65, 273, 389, 70, 26488, 63, 67, 8443, 8009, 1717, 24899, 70, 523, 86, 6275, 1769, 203, 3639, 399, 266, 345, 22498, 607, 6527, 273, 399, 266, 345, 22498, 607, 6527, 18, 1289, 24899, 70, 523, 86, 6275, 1769, 203, 3639, 389, 4963, 3088, 1283, 273, 399, 266, 345, 22498, 607, 6527, 31, 203, 540, 389, 11614, 1934, 1776, 3088, 1283, 273, 389, 11614, 1934, 1776, 3088, 1283, 18, 1717, 24899, 70, 523, 86, 6275, 1769, 203, 3639, 3626, 12279, 12, 2867, 24899, 8443, 3631, 1758, 12, 2211, 3631, 389, 70, 523, 86, 6275, 1769, 203, 3639, 389, 12645, 67, 323, 917, 1282, 63, 67, 8443, 6362, 67, 16351, 65, 273, 389, 12645, 67, 323, 917, 1282, 63, 67, 8443, 6362, 67, 16351, 8009, 1717, 24899, 2463, 6275, 1769, 203, 3639, 389, 13866, 27055, 24899, 8443, 16, 389, 16351, 16, 389, 2463, 6275, 1769, 203, 3639, 3626, 3423, 9446, 12, 2867, 24899, 8443, 3631, 389, 2463, 6275, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0xc9eB8Cce88F0d5CC30d8ccD0DB2e2F8645865B84/sources/Vault1155ERM.sol
* Lock out all non-management aspects of the contract. Token transfers are still allowed. */ Reentrancy guard.
function freeze() external { require(_status == S_NOT_ENTERED, "Reentrancy: reentrant call"); require((_addressRoles[msg.sender] & R_IS_ADMIN) == R_IS_ADMIN, "Not admin"); _status = S_FROZEN; }
8,533,895
[ 1, 2531, 596, 777, 1661, 17, 17381, 30494, 434, 326, 6835, 18, 3155, 29375, 854, 4859, 2935, 18, 342, 868, 8230, 12514, 11026, 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 ]
[ 1, 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, 16684, 1435, 3903, 288, 203, 3639, 2583, 24899, 2327, 422, 348, 67, 4400, 67, 12278, 2056, 16, 315, 426, 8230, 12514, 30, 283, 8230, 970, 745, 8863, 203, 3639, 2583, 12443, 67, 2867, 6898, 63, 3576, 18, 15330, 65, 473, 534, 67, 5127, 67, 15468, 13, 422, 534, 67, 5127, 67, 15468, 16, 315, 1248, 3981, 8863, 203, 203, 3639, 389, 2327, 273, 348, 67, 42, 1457, 62, 1157, 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 ]
pragma solidity 0.4.21; // 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)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // 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 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; } } // 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]); 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: 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); 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; } } // File: zeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: contracts/token/MintableTokenWithMinters.sol /** * @title Mintable Token with minters * @dev MintableToken, mintable by appointed minters */ contract MintableTokenWithMinters is MintableToken { mapping (address => bool) public minters; event MinterAdded(address indexed minter); event MinterRemoved(address indexed minter); /** * @dev Throws if called by any account other than the minter. */ modifier onlyMinter() { require(minters[msg.sender] == true); _; } /** * @dev The MintableToken constructor sets the first `minter` of the contract to the owner * account. */ function MintableTokenWithMinters() public { minters[owner] = true; // owner is minter } /** * @dev Function to mint tokens * @param _to The address to send new tokens to. * @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 onlyMinter canMint returns (bool) { // return super.mint(_to, _amount); // not used due to onlyOwner modifier totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Allows the owner to add a new minter. * @param newMinter The address to add as a minter. */ function addMinter(address newMinter) public onlyOwner { require(newMinter != address(0)); // not empty require(minters[newMinter] != true); // not already a minter emit MinterAdded(newMinter); minters[newMinter] = true; } /** * @dev Allows the owner to remove an existing minter. * @param minter The address to remove as a minter. */ function removeMinter(address minter) public onlyOwner { require(minter != owner); // cannot remove owner require(minters[minter] == true); // already a minter emit MinterRemoved(minter); delete minters[minter]; } } // File: zeppelin-solidity/contracts/token/ERC20/BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _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&#39;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: contracts/EtfToken.sol /** * @title FCTF 10 Coins token */ contract EtfToken is MintableTokenWithMinters, BurnableToken { string public constant name = "FCTF 10 Coins"; string public constant symbol = "10COINS"; uint8 public constant decimals = 8; function EtfToken() public { totalSupply_ = 0; } }
* @title Mintable Token with minters @dev MintableToken, mintable by appointed minters/
contract MintableTokenWithMinters is MintableToken { mapping (address => bool) public minters; event MinterAdded(address indexed minter); event MinterRemoved(address indexed minter); modifier onlyMinter() { require(minters[msg.sender] == true); _; } function MintableTokenWithMinters() public { } function mint(address _to, uint256 _amount) public onlyMinter canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function addMinter(address newMinter) public onlyOwner { emit MinterAdded(newMinter); minters[newMinter] = true; } function removeMinter(address minter) public onlyOwner { emit MinterRemoved(minter); delete minters[minter]; } }
6,774,714
[ 1, 49, 474, 429, 3155, 598, 1131, 5432, 225, 490, 474, 429, 1345, 16, 312, 474, 429, 635, 595, 763, 329, 1131, 5432, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 490, 474, 429, 1345, 1190, 49, 2761, 87, 353, 490, 474, 429, 1345, 288, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 1131, 5432, 31, 203, 203, 565, 871, 490, 2761, 8602, 12, 2867, 8808, 1131, 387, 1769, 203, 565, 871, 490, 2761, 10026, 12, 2867, 8808, 1131, 387, 1769, 203, 203, 203, 565, 9606, 1338, 49, 2761, 1435, 288, 203, 3639, 2583, 12, 1154, 5432, 63, 3576, 18, 15330, 65, 422, 638, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 490, 474, 429, 1345, 1190, 49, 2761, 87, 1435, 1071, 288, 203, 565, 289, 203, 203, 565, 445, 312, 474, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 1071, 1338, 49, 2761, 848, 49, 474, 1135, 261, 6430, 13, 288, 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, 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, 565, 445, 527, 49, 2761, 12, 2867, 394, 49, 2761, 13, 1071, 1338, 5541, 288, 203, 3639, 3626, 490, 2761, 8602, 12, 2704, 49, 2761, 1769, 203, 3639, 1131, 5432, 63, 2704, 49, 2761, 65, 273, 638, 31, 203, 565, 289, 203, 203, 565, 445, 1206, 49, 2761, 12, 2867, 1131, 387, 13, 1071, 2 ]
./full_match/11155111/0xe302e42153793088cbE5174a574BEcA7db27d213/sources/project_/contracts/MasterChef.sol
View function to see pending EQUALs on frontend.
function pendingEQUAL(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accEQUALPerShare = pool.accEQUALPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.timestamp > pool.lastRewardTime && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardTime, block.timestamp); uint256 equalReward = multiplier * equalPerSecond * pool.allocPoint / totalAllocPoint; accEQUALPerShare = accEQUALPerShare + (equalReward * 1e12 / lpSupply); } }
3,840,480
[ 1, 1767, 445, 358, 2621, 4634, 18231, 87, 603, 15442, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4634, 12853, 12, 11890, 5034, 389, 6610, 16, 1758, 389, 1355, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 67, 1355, 15533, 203, 3639, 2254, 5034, 4078, 12853, 2173, 9535, 273, 2845, 18, 8981, 12853, 2173, 9535, 31, 203, 3639, 2254, 5034, 12423, 3088, 1283, 273, 2845, 18, 9953, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 2629, 18, 5508, 405, 2845, 18, 2722, 17631, 1060, 950, 597, 12423, 3088, 1283, 480, 374, 13, 288, 203, 5411, 2254, 5034, 15027, 273, 31863, 5742, 12, 6011, 18, 2722, 17631, 1060, 950, 16, 1203, 18, 5508, 1769, 203, 5411, 2254, 5034, 3959, 17631, 1060, 273, 15027, 380, 3959, 2173, 8211, 380, 2845, 18, 9853, 2148, 342, 2078, 8763, 2148, 31, 203, 5411, 4078, 12853, 2173, 9535, 273, 4078, 12853, 2173, 9535, 397, 261, 9729, 17631, 1060, 380, 404, 73, 2138, 342, 12423, 3088, 1283, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-03-24 */ /** *Submitted for verification at Etherscan.io on 2021-10-30 */ // SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.4; 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; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library 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; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Address { 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); } 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"); (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract SAFUCT is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address payable public marketingAddress = payable(0xc88098bb4f7C1705107fcEfC8c2eA2d6701C18c4); mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private isBot; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1e9 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "SAFU Community Token"; string private _symbol = "SAFU CT"; uint8 private _decimals = 9; uint256 public _sellFee; uint256 public _buyFee; uint256 public _taxFee; uint256 private _previousTaxFee = _taxFee; uint256 private _liquidityFee; uint256 private _previousLiquidityFee = _liquidityFee; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwap; bool tradingOpen = false; bool canBlacklist = true; uint256 private _maxHoldings = 2200001 * 10**9; bool public maxHoldingsEnabled = true; uint256 public numTokensSellToAddToLiquidity = 2000000 * 10**9; event SwapETHForTokens( uint256 amountIn, address[] path ); event SwapTokensForETH( uint256 amountIn, address[] path ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _rOwned[_msgSender()] = _rTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function initContract() external onlyOwner() { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; } function oopenTrading() external onlyOwner() { _buyFee = 9; _sellFee = 18; _taxFee=1; tradingOpen = true; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from!= owner() && to!= owner()) { require(tradingOpen, "Trading not yet enabled."); //transfers disabled before openTrading require (!isBot[from] && !isBot[to], "Bot!"); } // buy if(from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to]) { if(maxHoldingsEnabled){ if(from == uniswapV2Pair && from != owner() && to != owner() && to != address(uniswapV2Router) && to != address(this)) { uint balance = balanceOf(to); require(balance.add(amount) <= _maxHoldings); } } _liquidityFee = _buyFee; } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; //sell if ( overMinTokenBalance && !inSwap && to == uniswapV2Pair ) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); _liquidityFee = _sellFee; } bool takeFee = false; //take fee only on swaps if ( (from==uniswapV2Pair || to==uniswapV2Pair) && !(_isExcludedFromFee[from] || _isExcludedFromFee[to]) ) { takeFee = true; } _tokenTransfer(from,to,amount,takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into thirds uint256 halfOfLiquify = contractTokenBalance.div(10); uint256 otherHalfOfLiquify = contractTokenBalance.div(10); uint256 portionForFees = contractTokenBalance.sub(halfOfLiquify).sub(otherHalfOfLiquify); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(halfOfLiquify); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalfOfLiquify, newBalance); sendETHToFee(portionForFees); emit SwapAndLiquify(halfOfLiquify, newBalance, otherHalfOfLiquify); } function sendETHToFee(uint256 amount) private { swapTokensForEth(amount); marketingAddress.call{value: address(this).balance}(""); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), // The contract block.timestamp ); emit SwapTokensForETH(tokenAmount, path); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { require (taxFee <= 1, "taxFee can't exceed 2%"); _taxFee = taxFee; } function setBuyFee(uint256 buyFee) external onlyOwner() { require (buyFee <= 9, "buy Fee can't exceed 2%"); _buyFee = buyFee; } function setSellFee(uint256 sellFee) external onlyOwner() { require (sellFee <= 9, "sell fee can't exceed 9%"); _sellFee = sellFee; } function setMarketingAddress(address _marketingAddress) external onlyOwner() { marketingAddress = payable(_marketingAddress); } function emergencyWithdraw() external onlyOwner { payable(owner()).transfer(address(this).balance); } function arrayBlacklist(address[] calldata bots) external onlyOwner() { require (canBlacklist == true, "can call this function only once"); uint256 iterator = 0; while(iterator < bots.length){ blacklist(bots[iterator]); iterator += 1; } canBlacklist = false; } function blacklist(address account) internal { if (account != uniswapV2Pair && account != owner() && account != address(this) && account!= address(uniswapV2Router)) { isBot[account] = true; } } function checkBot(address account) public view returns (bool) { return isBot[account]; } function removeBlacklist(address account) external onlyOwner { require (isBot[account], "Must be blacklisted"); isBot[account] = false; } function removeMaxHoldings() external onlyOwner() { maxHoldingsEnabled = false; } function setSwapThresholdAmount (uint256 amount) external onlyOwner { require (amount <= _tTotal.div(100), "can't exceed 1%"); numTokensSellToAddToLiquidity = amount * 10 ** 9; } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} }
buyadd liquiditytake fee only on swaps
function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from!= owner() && to!= owner()) { require (!isBot[from] && !isBot[to], "Bot!"); } if(from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to]) { if(maxHoldingsEnabled){ if(from == uniswapV2Pair && from != owner() && to != owner() && to != address(uniswapV2Router) && to != address(this)) { uint balance = balanceOf(to); require(balance.add(amount) <= _maxHoldings); } } _liquidityFee = _buyFee; } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; overMinTokenBalance && !inSwap && to == uniswapV2Pair ) { contractTokenBalance = numTokensSellToAddToLiquidity; swapAndLiquify(contractTokenBalance); _liquidityFee = _sellFee; } bool takeFee = false; if ( (from==uniswapV2Pair || to==uniswapV2Pair) && !(_isExcludedFromFee[from] || _isExcludedFromFee[to]) ) { takeFee = true; } _tokenTransfer(from,to,amount,takeFee); }
15,320,346
[ 1, 70, 9835, 1289, 4501, 372, 24237, 22188, 14036, 1338, 603, 1352, 6679, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 3238, 288, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 5912, 3844, 1297, 506, 6802, 2353, 3634, 8863, 203, 4202, 309, 261, 2080, 5, 33, 3410, 1435, 597, 358, 5, 33, 3410, 10756, 288, 203, 6647, 2583, 16051, 291, 6522, 63, 2080, 65, 597, 401, 291, 6522, 63, 869, 6487, 315, 6522, 4442, 1769, 203, 4202, 289, 203, 3639, 203, 3639, 309, 12, 2080, 422, 640, 291, 91, 438, 58, 22, 4154, 597, 358, 480, 1758, 12, 318, 291, 91, 438, 58, 22, 8259, 13, 597, 401, 67, 291, 16461, 1265, 14667, 63, 869, 5717, 288, 2398, 203, 5411, 309, 12, 1896, 20586, 899, 1526, 15329, 203, 7734, 309, 12, 2080, 422, 640, 291, 91, 438, 58, 22, 4154, 597, 628, 480, 3410, 1435, 597, 358, 480, 3410, 1435, 597, 358, 480, 1758, 12, 318, 291, 91, 438, 58, 22, 8259, 13, 597, 358, 480, 1758, 12, 2211, 3719, 288, 203, 10792, 2254, 11013, 273, 11013, 951, 12, 869, 1769, 203, 10792, 2583, 12, 12296, 18, 1289, 12, 8949, 13, 1648, 389, 1896, 20586, 899, 1769, 203, 7734, 289, 203, 5411, 289, 203, 2398, 203, 5411, 389, 549, 2 ]
./partial_match/1/0x702ecF93156962e9ffE53FeaD114Dbd54209B796/sources/ERC1155LazyPayableClaim.sol
* @dev Library used to query support of an interface declared via {IERC165}. Note that these functions return the actual result of the query: they do not `revert` if an interface is not supported. It is up to the caller to decide what to do in these cases./ As per the EIP-165 spec, no interface should ever match 0xffffffff
library ERC165Checker { bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; } function supportsERC165(address account) internal view returns (bool) { return supportsERC165InterfaceUnchecked(account, type(IERC165).interfaceId) && !supportsERC165InterfaceUnchecked(account, _INTERFACE_ID_INVALID); } function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { return supportsERC165(account) && supportsERC165InterfaceUnchecked(account, interfaceId); } function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); if (supportsERC165(account)) { for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = supportsERC165InterfaceUnchecked(account, interfaceIds[i]); } } return interfaceIdsSupported; } function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); if (supportsERC165(account)) { for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = supportsERC165InterfaceUnchecked(account, interfaceIds[i]); } } return interfaceIdsSupported; } function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); if (supportsERC165(account)) { for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = supportsERC165InterfaceUnchecked(account, interfaceIds[i]); } } return interfaceIdsSupported; } function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { if (!supportsERC165(account)) { return false; } for (uint256 i = 0; i < interfaceIds.length; i++) { if (!supportsERC165InterfaceUnchecked(account, interfaceIds[i])) { return false; } } } function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { if (!supportsERC165(account)) { return false; } for (uint256 i = 0; i < interfaceIds.length; i++) { if (!supportsERC165InterfaceUnchecked(account, interfaceIds[i])) { return false; } } } function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { if (!supportsERC165(account)) { return false; } for (uint256 i = 0; i < interfaceIds.length; i++) { if (!supportsERC165InterfaceUnchecked(account, interfaceIds[i])) { return false; } } } function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { if (!supportsERC165(account)) { return false; } for (uint256 i = 0; i < interfaceIds.length; i++) { if (!supportsERC165InterfaceUnchecked(account, interfaceIds[i])) { return false; } } } return true; function supportsERC165InterfaceUnchecked(address account, bytes4 interfaceId) internal view returns (bool) { bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId); bool success; uint256 returnSize; uint256 returnValue; assembly { success := staticcall(30000, account, add(encodedParams, 0x20), mload(encodedParams), 0x00, 0x20) returnSize := returndatasize() returnValue := mload(0x00) } return success && returnSize >= 0x20 && returnValue > 0; } function supportsERC165InterfaceUnchecked(address account, bytes4 interfaceId) internal view returns (bool) { bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId); bool success; uint256 returnSize; uint256 returnValue; assembly { success := staticcall(30000, account, add(encodedParams, 0x20), mload(encodedParams), 0x00, 0x20) returnSize := returndatasize() returnValue := mload(0x00) } return success && returnSize >= 0x20 && returnValue > 0; } }
3,681,453
[ 1, 9313, 1399, 358, 843, 2865, 434, 392, 1560, 7886, 3970, 288, 45, 654, 39, 28275, 5496, 3609, 716, 4259, 4186, 327, 326, 3214, 563, 434, 326, 843, 30, 2898, 741, 486, 1375, 266, 1097, 68, 309, 392, 1560, 353, 486, 3260, 18, 2597, 353, 731, 358, 326, 4894, 358, 16288, 4121, 358, 741, 316, 4259, 6088, 18, 19, 2970, 1534, 326, 512, 2579, 17, 28275, 857, 16, 1158, 1560, 1410, 14103, 845, 374, 28857, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4232, 39, 28275, 8847, 288, 203, 565, 1731, 24, 3238, 5381, 389, 18865, 67, 734, 67, 9347, 273, 374, 28857, 31, 203, 203, 97, 203, 203, 203, 565, 445, 6146, 654, 39, 28275, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 203, 5411, 6146, 654, 39, 28275, 1358, 984, 4532, 12, 4631, 16, 618, 12, 45, 654, 39, 28275, 2934, 5831, 548, 13, 597, 203, 5411, 401, 28064, 654, 39, 28275, 1358, 984, 4532, 12, 4631, 16, 389, 18865, 67, 734, 67, 9347, 1769, 203, 565, 289, 203, 203, 565, 445, 6146, 1358, 12, 2867, 2236, 16, 1731, 24, 1560, 548, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 6146, 654, 39, 28275, 12, 4631, 13, 597, 6146, 654, 39, 28275, 1358, 984, 4532, 12, 4631, 16, 1560, 548, 1769, 203, 565, 289, 203, 203, 565, 445, 25008, 10273, 12, 2867, 2236, 16, 1731, 24, 8526, 3778, 1560, 2673, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 6430, 8526, 3778, 13, 203, 565, 288, 203, 3639, 1426, 8526, 3778, 1560, 2673, 7223, 273, 394, 1426, 8526, 12, 5831, 2673, 18, 2469, 1769, 203, 203, 3639, 309, 261, 28064, 654, 39, 28275, 12, 4631, 3719, 288, 203, 5411, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1560, 2673, 18, 2469, 31, 277, 27245, 288, 203, 7734, 1560, 2673, 7223, 63, 77, 65, 273, 6146, 654, 39, 28275, 1358, 984, 4532, 12, 4631, 16, 1560, 2673, 63, 77, 19226, 203, 5411, 2 ]
./partial_match/42/0xbBF04E0f4C31Ff39520227C170e29cb2bAf5787b/sources/RewardEscrow.sol
ERROR: type should be string, got " https:docs.pynthetix.io/contracts/source/interfaces/irewardescrow Views Mutative functions"
interface IRewardEscrow { function balanceOf(address account) external view returns (uint); function numVestingEntries(address account) external view returns (uint); function totalEscrowedAccountBalance(address account) external view returns (uint); function totalVestedAccountBalance(address account) external view returns (uint); function appendVestingEntry(address account, uint quantity) external; function vest() external; }
3,308,418
[ 1, 4528, 30, 8532, 18, 84, 878, 451, 278, 697, 18, 1594, 19, 16351, 87, 19, 3168, 19, 15898, 19, 577, 2913, 742, 492, 31117, 14138, 1535, 4186, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 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, 5831, 15908, 359, 1060, 6412, 492, 288, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 1769, 203, 203, 565, 445, 818, 58, 10100, 5400, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 1769, 203, 203, 565, 445, 2078, 6412, 492, 329, 3032, 13937, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 1769, 203, 203, 565, 445, 2078, 58, 3149, 3032, 13937, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 1769, 203, 203, 565, 445, 714, 58, 10100, 1622, 12, 2867, 2236, 16, 2254, 10457, 13, 3903, 31, 203, 203, 565, 445, 331, 395, 1435, 3903, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "./interfaces/IPlus.sol"; /** * @title Plus token base contract. * * Plus token is a value pegged ERC20 token which provides global interest to all holders. * It can be categorized as single plus token and composite plus token: * * Single plus token is backed by one ERC20 token and targeted at yield generation. * Composite plus token is backed by a basket of ERC20 token and targeted at better basket management. */ abstract contract Plus is ERC20Upgradeable, IPlus { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; /** * @dev Emitted each time the share of a user is updated. */ event UserShareUpdated(address indexed account, uint256 oldShare, uint256 newShare, uint256 totalShares); event Rebased(uint256 oldIndex, uint256 newIndex, uint256 totalUnderlying); event Donated(address indexed account, uint256 amount, uint256 share); event GovernanceUpdated(address indexed oldGovernance, address indexed newGovernance); event StrategistUpdated(address indexed strategist, bool allowed); event TreasuryUpdated(address indexed oldTreasury, address indexed newTreasury); event RedeemFeeUpdated(uint256 oldFee, uint256 newFee); event MintPausedUpdated(address indexed token, bool paused); uint256 public constant MAX_PERCENT = 10000; // 0.01% uint256 public constant WAD = 1e18; /** * @dev Struct to represent a rebase hook. */ struct Transaction { bool enabled; address destination; bytes data; } // Rebase hooks Transaction[] public transactions; uint256 public totalShares; mapping(address => uint256) public userShare; // The exchange rate between total shares and BTC+ total supply. Express in WAD. // It's equal to the amount of plus token per share. // Note: The index will never decrease! uint256 public index; address public override governance; mapping(address => bool) public override strategists; address public override treasury; // Governance parameters uint256 public redeemFee; // EIP 2612: Permit // Credit: https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; /** * @dev Initializes the plus token contract. */ function __PlusToken__init(string memory _name, string memory _symbol) internal initializer { __ERC20_init(_name, _symbol); index = WAD; governance = msg.sender; treasury = msg.sender; uint _chainId; assembly { _chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(_name)), keccak256(bytes('1')), _chainId, address(this) ) ); } function _checkGovernance() internal view { require(msg.sender == governance, "not governance"); } modifier onlyGovernance() { _checkGovernance(); _; } function _checkStrategist() internal view { require(msg.sender == governance || strategists[msg.sender], "not strategist"); } modifier onlyStrategist { _checkStrategist(); _; } /** * @dev Returns the total value of the plus token in terms of the peg value in WAD. * All underlying token amounts have been scaled to 18 decimals, then expressed in WAD. */ function _totalUnderlyingInWad() internal view virtual returns (uint256); /** * @dev Returns the total value of the plus token in terms of the peg value. * For single plus, it's equal to its total supply. * For composite plus, it's equal to the total amount of single plus tokens in its basket. */ function totalUnderlying() external view override returns (uint256) { return _totalUnderlyingInWad().div(WAD); } /** * @dev Returns the total supply of plus token. See {IERC20Updateable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return totalShares.mul(index).div(WAD); } /** * @dev Returns the balance of plus token for the account. See {IERC20Updateable-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return userShare[account].mul(index).div(WAD); } /** * @dev Returns the current liquidity ratio of the plus token in WAD. */ function liquidityRatio() public view returns (uint256) { uint256 _totalSupply = totalSupply(); return _totalSupply == 0 ? WAD : _totalUnderlyingInWad().div(_totalSupply); } /** * @dev Accrues interest to increase index. */ function rebase() public override { uint256 _totalShares = totalShares; if (_totalShares == 0) return; // underlying is in WAD, and index is also in WAD uint256 _underlying = _totalUnderlyingInWad(); uint256 _oldIndex = index; uint256 _newIndex = _underlying.div(_totalShares); // _newIndex - oldIndex is the amount of interest generated for each share // _oldIndex might be larger than _newIndex in a short period of time. In this period, the liquidity ratio is smaller than 1. if (_newIndex > _oldIndex) { // Index can never decrease index = _newIndex; for (uint256 i = 0; i < transactions.length; i++) { Transaction storage transaction = transactions[i]; if (transaction.enabled) { (bool success, ) = transaction.destination.call(transaction.data); require(success, "rebase hook failed"); } } // In this event we are returning underlyiing() which can be used to compute the actual interest generated. emit Rebased(_oldIndex, _newIndex, _underlying.div(WAD)); } } /** * @dev Allows anyone to donate their plus asset to all other holders. * @param _amount Amount of plus token to donate. */ function donate(uint256 _amount) public override { // Rebase first to make index up-to-date rebase(); // Special handling of -1 is required here in order to fully donate all shares, since interest // will be accrued between the donate transaction is signed and mined. uint256 _share; if (_amount == uint256(int256(-1))) { _share = userShare[msg.sender]; _amount = _share.mul(index).div(WAD); } else { _share = _amount.mul(WAD).div(index); } uint256 _oldShare = userShare[msg.sender]; uint256 _newShare = _oldShare.sub(_share, "insufficient share"); uint256 _newTotalShares = totalShares.sub(_share); userShare[msg.sender] = _newShare; totalShares = _newTotalShares; emit UserShareUpdated(msg.sender, _oldShare, _newShare, _newTotalShares); emit Donated(msg.sender, _amount, _share); } /** * @dev Moves tokens `amount` from `sender` to `recipient`. */ function _transfer(address _sender, address _recipient, uint256 _amount) internal virtual override { require(_sender != _recipient, "recipient cannot be sender"); // Rebase first to make index up-to-date rebase(); uint256 _shareToTransfer = _amount.mul(WAD).div(index); uint256 _oldSenderShare = userShare[_sender]; uint256 _newSenderShare = _oldSenderShare.sub(_shareToTransfer, "insufficient share"); uint256 _oldRecipientShare = userShare[_recipient]; uint256 _newRecipientShare = _oldRecipientShare.add(_shareToTransfer); uint256 _totalShares = totalShares; userShare[_sender] = _newSenderShare; userShare[_recipient] = _newRecipientShare; emit UserShareUpdated(_sender, _oldSenderShare, _newSenderShare, _totalShares); emit UserShareUpdated(_recipient, _oldRecipientShare, _newRecipientShare, _totalShares); } /** * @dev Gassless approve. */ function permit(address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s) external { require(_deadline >= block.timestamp, 'expired'); 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 signature'); _approve(_owner, _spender, _value); } /********************************************* * * Governance methods * **********************************************/ /** * @dev Updates governance. Only governance can update governance. */ function setGovernance(address _governance) external onlyGovernance { address _oldGovernance = governance; governance = _governance; emit GovernanceUpdated(_oldGovernance, _governance); } /** * @dev Updates strategist. Both governance and strategists can update strategist. */ function setStrategist(address _strategist, bool _allowed) external onlyStrategist { require(_strategist != address(0x0), "strategist not set"); strategists[_strategist] = _allowed; emit StrategistUpdated(_strategist, _allowed); } /** * @dev Updates the treasury. Only governance can update treasury. */ function setTreasury(address _treasury) external onlyGovernance { require(_treasury != address(0x0), "treasury not set"); address _oldTreasury = treasury; treasury = _treasury; emit TreasuryUpdated(_oldTreasury, _treasury); } /** * @dev Updates the redeem fee. Only governance can update redeem fee. */ function setRedeemFee(uint256 _redeemFee) external onlyGovernance { require(_redeemFee <= MAX_PERCENT, "redeem fee too big"); uint256 _oldFee = redeemFee; redeemFee = _redeemFee; emit RedeemFeeUpdated(_oldFee, _redeemFee); } /** * @dev Used to salvage any ETH deposited to BTC+ contract by mistake. Only strategist can salvage ETH. * The salvaged ETH is transferred to treasury for futher operation. */ function salvage() external onlyStrategist { uint256 _amount = address(this).balance; address payable _target = payable(treasury); (bool _success, ) = _target.call{value: _amount}(new bytes(0)); require(_success, 'ETH salvage failed'); } /** * @dev Checks whether a token can be salvaged via salvageToken(). * @param _token Token to check salvageability. */ function _salvageable(address _token) internal view virtual returns (bool); /** * @dev Used to salvage any token deposited to plus contract by mistake. Only strategist can salvage token. * The salvaged token is transferred to treasury for futhuer operation. * @param _token Address of the token to salvage. */ function salvageToken(address _token) external onlyStrategist { require(_token != address(0x0), "token not set"); require(_salvageable(_token), "cannot salvage"); IERC20Upgradeable _target = IERC20Upgradeable(_token); _target.safeTransfer(treasury, _target.balanceOf(address(this))); } /** * @dev Add a new rebase hook. * @param _destination Destination contract for the reabase hook. * @param _data Transaction payload for the rebase hook. */ function addTransaction(address _destination, bytes memory _data) external onlyGovernance { transactions.push(Transaction({enabled: true, destination: _destination, data: _data})); } /** * @dev Remove a rebase hook. * @param _index Index of the transaction to remove. */ function removeTransaction(uint256 _index) external onlyGovernance { require(_index < transactions.length, "index out of bounds"); if (_index < transactions.length - 1) { transactions[_index] = transactions[transactions.length - 1]; } transactions.pop(); } /** * @dev Updates an existing rebase hook transaction. * @param _index Index of transaction. Transaction ordering may have changed since adding. * @param _enabled True for enabled, false for disabled. */ function updateTransaction(uint256 _index, bool _enabled) external onlyGovernance { require(_index < transactions.length, "index must be in range of stored tx list"); transactions[_index].enabled = _enabled; } /** * @dev Returns the number of rebase hook transactions. */ function transactionSize() external view returns (uint256) { return transactions.length; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "./interfaces/ISinglePlus.sol"; import "./Plus.sol"; /** * @title Single plus token. * * A single plus token wraps an underlying ERC20 token, typically a yield token, * into a value peg token. */ contract SinglePlus is ISinglePlus, Plus, ReentrancyGuardUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; event Minted(address indexed user, uint256 amount, uint256 mintShare, uint256 mintAmount); event Redeemed(address indexed user, uint256 amount, uint256 redeemShare, uint256 redeemAmount, uint256 fee); event Harvested(address indexed token, uint256 amount, uint256 feeAmount); event PerformanceFeeUpdated(uint256 oldPerformanceFee, uint256 newPerformanceFee); // Underlying token of the single plus toke. Typically a yield token and not value peg. address public override token; // Whether minting is paused for the single plus token. bool public mintPaused; uint256 public performanceFee; uint256 public constant PERCENT_MAX = 10000; // 0.01% /** * @dev Initializes the single plus contract. * @param _token Underlying token of the single plus. * @param _nameOverride If empty, the single plus name will be `token_name Plus` * @param _symbolOverride If empty. the single plus name will be `token_symbol+` */ function initialize(address _token, string memory _nameOverride, string memory _symbolOverride) public initializer { token = _token; string memory _name = _nameOverride; string memory _symbol = _symbolOverride; if (bytes(_name).length == 0) { _name = string(abi.encodePacked(ERC20Upgradeable(_token).name(), " Plus")); } if (bytes(_symbol).length == 0) { _symbol = string(abi.encodePacked(ERC20Upgradeable(_token).symbol(), "+")); } __PlusToken__init(_name, _symbol); __ReentrancyGuard_init(); } /** * @dev Returns the amount of single plus tokens minted with the underlying token provided. * @dev _amounts Amount of underlying token used to mint the single plus token. */ function getMintAmount(uint256 _amount) external view returns(uint256) { // Conversion rate is the amount of single plus token per underlying token, in WAD. return _amount.mul(_conversionRate()).div(WAD); } /** * @dev Mints the single plus token with the underlying token. * @dev _amount Amount of the underlying token used to mint single plus token. */ function mint(uint256 _amount) external override nonReentrant { require(_amount > 0, "zero amount"); require(!mintPaused, "mint paused"); // Rebase first to make index up-to-date rebase(); // Transfers the underlying token in. IERC20Upgradeable(token).safeTransferFrom(msg.sender, address(this), _amount); // Conversion rate is the amount of single plus token per underlying token, in WAD. uint256 _newAmount = _amount.mul(_conversionRate()).div(WAD); // Index is in WAD uint256 _share = _amount.mul(_conversionRate()).div(index); uint256 _oldShare = userShare[msg.sender]; uint256 _newShare = _oldShare.add(_share); uint256 _totalShares = totalShares.add(_share); totalShares = _totalShares; userShare[msg.sender] = _newShare; emit UserShareUpdated(msg.sender, _oldShare, _newShare, _totalShares); emit Minted(msg.sender, _amount, _share, _newAmount); } /** * @dev Returns the amount of tokens received in redeeming the single plus token. * @param _amount Amounf of single plus to redeem. * @return Amount of underlying token received as well as fee collected. */ function getRedeemAmount(uint256 _amount) external view returns (uint256, uint256) { // Withdraw ratio = min(liquidity ratio, 1 - redeem fee) // Liquidity ratio is in WAD and redeem fee is in 0.01% uint256 _withdrawAmount1 = _amount.mul(liquidityRatio()).div(WAD); uint256 _withdrawAmount2 = _amount.mul(MAX_PERCENT - redeemFee).div(MAX_PERCENT); uint256 _withdrawAmount = MathUpgradeable.min(_withdrawAmount1, _withdrawAmount2); uint256 _fee = _amount.sub(_withdrawAmount); // Conversion rate is in WAD uint256 _underlyingAmount = _withdrawAmount.mul(WAD).div(_conversionRate()); // Note: Fee is in plus token(18 decimals) but the received amount is in underlying token! return (_underlyingAmount, _fee); } /** * @dev Redeems the single plus token. * @param _amount Amount of single plus token to redeem. -1 means redeeming all shares. */ function redeem(uint256 _amount) external override nonReentrant { require(_amount > 0, "zero amount"); // Rebase first to make index up-to-date rebase(); // Special handling of -1 is required here in order to fully redeem all shares, since interest // will be accrued between the redeem transaction is signed and mined. uint256 _share; if (_amount == uint256(int256(-1))) { _share = userShare[msg.sender]; _amount = _share.mul(index).div(WAD); } else { _share = _amount.mul(WAD).div(index); } // Withdraw ratio = min(liquidity ratio, 1 - redeem fee) // Liquidity ratio is in WAD and redeem fee is in 0.01% uint256 _withdrawAmount1 = _amount.mul(liquidityRatio()).div(WAD); uint256 _withdrawAmount2 = _amount.mul(MAX_PERCENT - redeemFee).div(MAX_PERCENT); uint256 _withdrawAmount = MathUpgradeable.min(_withdrawAmount1, _withdrawAmount2); uint256 _fee = _amount.sub(_withdrawAmount); // Conversion rate is in WAD uint256 _underlyingAmount = _withdrawAmount.mul(WAD).div(_conversionRate()); _withdraw(msg.sender, _underlyingAmount); // Updates the balance uint256 _oldShare = userShare[msg.sender]; uint256 _newShare = _oldShare.sub(_share); totalShares = totalShares.sub(_share); userShare[msg.sender] = _newShare; emit UserShareUpdated(msg.sender, _oldShare, _newShare, totalShares); emit Redeemed(msg.sender, _underlyingAmount, _share, _amount, _fee); } /** * @dev Updates the mint paused state of the underlying token. * @param _paused Whether minting with that token is paused. */ function setMintPaused(bool _paused) external onlyStrategist { require(mintPaused != _paused, "no change"); mintPaused = _paused; emit MintPausedUpdated(token, _paused); } /** * @dev Updates the performance fee. Only governance can update the performance fee. */ function setPerformanceFee(uint256 _performanceFee) public onlyGovernance { require(_performanceFee <= PERCENT_MAX, "overflow"); uint256 oldPerformanceFee = performanceFee; performanceFee = _performanceFee; emit PerformanceFeeUpdated(oldPerformanceFee, _performanceFee); } /** * @dev Retrive the underlying assets from the investment. */ function divest() public virtual override {} /** * @dev Returns the amount that can be invested now. The invested token * does not have to be the underlying token. * investable > 0 means it's time to call invest. */ function investable() public view virtual override returns (uint256) { return 0; } /** * @dev Invest the underlying assets for additional yield. */ function invest() public virtual override {} /** * @dev Returns the amount of reward that could be harvested now. * harvestable > 0 means it's time to call harvest. */ function harvestable() public view virtual override returns (uint256) { return 0; } /** * @dev Harvest additional yield from the investment. */ function harvest() public virtual override {} /** * @dev Checks whether a token can be salvaged via salvageToken(). * @param _token Token to check salvageability. */ function _salvageable(address _token) internal view virtual override returns (bool) { // For single plus, the only token that cannot salvage is the underlying token! return _token != token; } /** * @dev Returns the amount of single plus token is worth for one underlying token, expressed in WAD. * The default implmentation assumes that the single plus and underlying tokens are both peg. */ function _conversionRate() internal view virtual returns (uint256) { // 36 since the decimals for plus token is always 18, and conversion rate is in WAD. return uint256(10) ** (36 - ERC20Upgradeable(token).decimals()); } /** * @dev Returns the total value of the underlying token in terms of the peg value, scaled to 18 decimals * and expressed in WAD. */ function _totalUnderlyingInWad() internal view virtual override returns (uint256) { uint256 _balance = IERC20Upgradeable(token).balanceOf(address(this)); // Conversion rate is the amount of single plus token per underlying token, in WAD. return _balance.mul(_conversionRate()); } /** * @dev Withdraws underlying tokens. * @param _receiver Address to receive the token withdraw. * @param _amount Amount of underlying token withdraw. */ function _withdraw(address _receiver, uint256 _amount) internal virtual { IERC20Upgradeable(token).safeTransfer(_receiver, _amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; /** * @dev Interfaces for converter. */ interface IConverter { function convert(address _from, address _to, uint256 _fromAmount, uint256 _toAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; /** * @title Interface for plus token. * Plus token is a value pegged ERC20 token which provides global interest to all holders. */ interface IPlus { /** * @dev Returns the governance address. */ function governance() external view returns (address); /** * @dev Returns whether the account is a strategist. */ function strategists(address _account) external view returns (bool); /** * @dev Returns the treasury address. */ function treasury() external view returns (address); /** * @dev Accrues interest to increase index. */ function rebase() external; /** * @dev Returns the total value of the plus token in terms of the peg value. */ function totalUnderlying() external view returns (uint256); /** * @dev Allows anyone to donate their plus asset to all other holders. * @param _amount Amount of plus token to donate. */ function donate(uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "./IPlus.sol"; /** * @title Interface for single plus token. * Single plus token is backed by one ERC20 token and targeted at yield generation. */ interface ISinglePlus is IPlus { /** * @dev Returns the address of the underlying token. */ function token() external view returns (address); /** * @dev Retrive the underlying assets from the investment. */ function divest() external; /** * @dev Returns the amount that can be invested now. The invested token * does not have to be the underlying token. * investable > 0 means it's time to call invest. */ function investable() external view returns (uint256); /** * @dev Invest the underlying assets for additional yield. */ function invest() external; /** * @dev Returns the amount of reward that could be harvested now. * harvestable > 0 means it's time to call harvest. */ function harvestable() external view returns (uint256); /** * @dev Harvest additional yield from the investment. */ function harvest() external; /** * @dev Mints the single plus token with the underlying token. * @dev _amount Amount of the underlying token used to mint single plus token. */ function mint(uint256 _amount) external; /** * @dev Redeems the single plus token. * @param _amount Amount of single plus token to redeem. -1 means redeeming all shares. */ function redeem(uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; /** * @dev Interface for Badger Geyser. */ interface IBadgerGeyser { /** * @param _addr The user to look up staking information for. * @return The number of staking tokens deposited for addr. */ function totalStakedFor(address _addr) external view returns (uint256); /** * @dev Transfers amount of deposit tokens from the user. * @param _amount Number of deposit tokens to stake. */ function stake(uint256 _amount, bytes calldata _data) external; /** * @dev Unstakes a certain amount of previously deposited tokens. User also receives their * alotted number of distribution tokens. * @param _amount Number of deposit tokens to unstake / withdraw. * @param _data Not used. */ function unstake(uint256 _amount, bytes calldata _data) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; /** * @dev Interface for Badger Sett. */ interface IBadgerSett { function getPricePerFullShare() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; /** * @dev Interface for Badger Tree. */ interface IBadgerTree { /// @notice Claim accumulated rewards for a set of tokens at a given cycle number function claim( address[] calldata tokens, uint256[] calldata cumulativeAmounts, uint256 index, uint256 cycle, bytes32[] calldata merkleProof, uint256[] calldata amountsToClaim ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; /** * @notice Interface for Curve.fi's pool. */ interface ICurveFi { function get_virtual_price() external view returns (uint256); function remove_liquidity_one_coin(uint256 token_amount, int128 iint128, uint256 min_amount) external; // ren pool/hbtc pool function add_liquidity( uint256[2] calldata amounts, uint256 min_mint_amount ) external; function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[2] calldata amounts) external; // sbtc pool function add_liquidity( uint256[3] calldata amounts, uint256 min_mint_amount ) external; function remove_liquidity_imbalance(uint256[3] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[3] calldata amounts) external; // obtc pool function add_liquidity( uint256[4] calldata amounts, uint256 min_mint_amount ) external; function remove_liquidity_imbalance(uint256[4] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; /** * @notice Interface for Uniswap's router. */ interface IUniswapRouter { function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "../../SinglePlus.sol"; import "../../interfaces/IConverter.sol"; import "../../interfaces/curve/ICurveFi.sol"; import "../../interfaces/badger/IBadgerSett.sol"; import "../../interfaces/badger/IBadgerGeyser.sol"; import "../../interfaces/badger/IBadgerTree.sol"; import "../../interfaces/uniswap/IUniswapRouter.sol"; /** * @dev Single plus for Badger renCrv. */ contract BadgerRenCrvPlus is SinglePlus { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; address public constant BADGER_RENCRV = address(0x6dEf55d2e18486B9dDfaA075bc4e4EE0B28c1545); address public constant BADGER_RENCRV_STAKING = address(0x2296f174374508278DC12b806A7f27c87D53Ca15); address public constant BADGER_TREE = address(0x660802Fc641b154aBA66a62137e71f331B6d787A); address public constant WBTC = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); address public constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address public constant BADGER = address(0x3472A5A71965499acd81997a54BBA8D852C6E53d); address public constant DIGG = address(0x798D1bE841a82a273720CE31c822C61a67a601C3); address public constant RENCRV = address(0x49849C98ae39Fff122806C06791Fa73784FB3675); address public constant UNISWAP = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Uniswap RouterV2 address public constant REN_SWAP = address(0x93054188d876f558f4a66B2EF1d97d16eDf0895B); // REN swap address public converter; /** * @dev Initializes brenCrv+. */ function initialize(address _converter) public initializer { SinglePlus.initialize(BADGER_RENCRV, "", ""); converter = _converter; } /** * @dev Retrive the underlying assets from the investment. * Only governance or strategist can call this function. */ function divest() public virtual override onlyStrategist { IBadgerGeyser _geyser = IBadgerGeyser(BADGER_RENCRV_STAKING); _geyser.unstake(_geyser.totalStakedFor(address(this)), ''); } /** * @dev Returns the amount that can be invested now. The invested token * does not have to be the underlying token. * investable > 0 means it's time to call invest. */ function investable() public view virtual override returns (uint256) { return IERC20Upgradeable(BADGER_RENCRV).balanceOf(address(this)); } /** * @dev Invest the underlying assets for additional yield. * Only governance or strategist can call this function. */ function invest() public virtual override onlyStrategist { IERC20Upgradeable _token = IERC20Upgradeable(BADGER_RENCRV); uint256 _balance = _token.balanceOf(address(this)); if (_balance > 0) { _token.safeApprove(BADGER_RENCRV_STAKING, 0); _token.safeApprove(BADGER_RENCRV_STAKING, _balance); IBadgerGeyser(BADGER_RENCRV_STAKING).stake(_balance, ''); } } /** * @dev Harvest additional yield from the investment. * Only governance or strategist can call this function. */ function harvest(address[] calldata _tokens, uint256[] calldata _cumulativeAmounts, uint256 _index, uint256 _cycle, bytes32[] calldata _merkleProof, uint256[] calldata _amountsToClaim) public virtual onlyStrategist { // 1. Harvest from Badger Tree IBadgerTree(BADGER_TREE).claim(_tokens, _cumulativeAmounts, _index, _cycle, _merkleProof, _amountsToClaim); // 2. Badger --> WETH --> WBTC uint256 _badger = IERC20Upgradeable(BADGER).balanceOf(address(this)); if (_badger > 0) { IERC20Upgradeable(BADGER).safeApprove(UNISWAP, 0); IERC20Upgradeable(BADGER).safeApprove(UNISWAP, _badger); address[] memory _path = new address[](3); _path[0] = BADGER; _path[1] = WETH; _path[2] = WBTC; IUniswapRouter(UNISWAP).swapExactTokensForTokens(_badger, uint256(0), _path, address(this), block.timestamp.add(1800)); } // 3: Digg --> WBTC uint256 _digg = IERC20Upgradeable(DIGG).balanceOf(address(this)); if (_digg > 0) { IERC20Upgradeable(DIGG).safeApprove(UNISWAP, 0); IERC20Upgradeable(DIGG).safeApprove(UNISWAP, _digg); address[] memory _path = new address[](2); _path[0] = DIGG; _path[1] = WBTC; IUniswapRouter(UNISWAP).swapExactTokensForTokens(_digg, uint256(0), _path, address(this), block.timestamp.add(1800)); } // 4: WBTC --> renCrv uint256 _wbtc = IERC20Upgradeable(WBTC).balanceOf(address(this)); if (_wbtc == 0) return; // If there is performance fee, charged in WBTC uint256 _fee = 0; if (performanceFee > 0) { _fee = _wbtc.mul(performanceFee).div(PERCENT_MAX); IERC20Upgradeable(WBTC).safeTransfer(treasury, _fee); _wbtc = _wbtc.sub(_fee); } IERC20Upgradeable(WBTC).safeApprove(REN_SWAP, 0); IERC20Upgradeable(WBTC).safeApprove(REN_SWAP, _wbtc); ICurveFi(REN_SWAP).add_liquidity([0, _wbtc], 0); // 5: renCrv --> brenCrv address _converter = converter; uint256 _renCrv = IERC20Upgradeable(RENCRV).balanceOf(address(this)); IERC20Upgradeable(RENCRV).safeApprove(_converter, 0); IERC20Upgradeable(RENCRV).safeApprove(_converter, _renCrv); uint256 _before = IERC20Upgradeable(BADGER_RENCRV).balanceOf(address(this)); uint256 _target = _renCrv.mul(WAD).div(IBadgerSett(BADGER_RENCRV).getPricePerFullShare()); IConverter(_converter).convert(RENCRV, BADGER_RENCRV, _renCrv, _target); uint256 _after = IERC20Upgradeable(BADGER_RENCRV).balanceOf(address(this)); require(_after >= _before.add(_target), "convert fail"); invest(); // Also it's a good time to rebase! rebase(); emit Harvested(BADGER_RENCRV, _wbtc, _fee); } /** * @dev Checks whether a token can be salvaged via salvageToken(). The following * tokens are not salvageable: * 1) brenCrv * 2) renCrv * @param _token Token to check salvageability. */ function _salvageable(address _token) internal view virtual override returns (bool) { return _token != BADGER_RENCRV && _token != RENCRV; } /** * @dev Returns the amount of single plus token is worth for one underlying token, expressed in WAD. */ function _conversionRate() internal view virtual override returns (uint256) { // Both Badger's share price and Curve's virtual price are in WAD return IBadgerSett(BADGER_RENCRV).getPricePerFullShare().mul(ICurveFi(REN_SWAP).get_virtual_price()).div(WAD); } /** * @dev Returns the total value of the underlying token in terms of the peg value, scaled to 18 decimals * and expressed in WAD. */ function _totalUnderlyingInWad() internal view virtual override returns (uint256) { uint256 _balance = IERC20Upgradeable(BADGER_RENCRV).balanceOf(address(this)); uint256 _staked = IBadgerGeyser(BADGER_RENCRV_STAKING).totalStakedFor(address(this)); // Conversion rate is the amount of single plus token per underlying token, in WAD. return _balance.add(_staked).mul(_conversionRate()); } /** * @dev Withdraws underlying tokens. * @param _receiver Address to receive the token withdraw. * @param _amount Amount of underlying token withdraw. */ function _withdraw(address _receiver, uint256 _amount) internal virtual override { IERC20Upgradeable _token = IERC20Upgradeable(BADGER_RENCRV); uint256 _balance = _token.balanceOf(address(this)); if (_balance < _amount) { IBadgerGeyser(BADGER_RENCRV_STAKING).unstake(_amount.sub(_balance), ''); // In case of rounding errors _amount = MathUpgradeable.min(_amount, _token.balanceOf(address(this))); } _token.safeTransfer(_receiver, _amount); } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version 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 {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ 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_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overloaded; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT 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 no longer needed starting with Solidity 0.8. 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. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
* @dev Returns the total value of the underlying token in terms of the peg value, scaled to 18 decimals and expressed in WAD./ Conversion rate is the amount of single plus token per underlying token, in WAD.
function _totalUnderlyingInWad() internal view virtual override returns (uint256) { uint256 _balance = IERC20Upgradeable(BADGER_RENCRV).balanceOf(address(this)); uint256 _staked = IBadgerGeyser(BADGER_RENCRV_STAKING).totalStakedFor(address(this)); return _balance.add(_staked).mul(_conversionRate()); }
10,113,025
[ 1, 1356, 326, 2078, 460, 434, 326, 6808, 1147, 316, 6548, 434, 326, 29231, 460, 16, 12304, 358, 6549, 15105, 471, 26863, 316, 678, 1880, 18, 19, 16401, 4993, 353, 326, 3844, 434, 2202, 8737, 1147, 1534, 6808, 1147, 16, 316, 678, 1880, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 389, 4963, 14655, 6291, 382, 59, 361, 1435, 2713, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 389, 12296, 273, 467, 654, 39, 3462, 10784, 429, 12, 16234, 3101, 67, 24296, 5093, 58, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 389, 334, 9477, 273, 467, 6434, 693, 43, 402, 550, 12, 16234, 3101, 67, 24296, 5093, 58, 67, 882, 14607, 1360, 2934, 4963, 510, 9477, 1290, 12, 2867, 12, 2211, 10019, 203, 203, 3639, 327, 389, 12296, 18, 1289, 24899, 334, 9477, 2934, 16411, 24899, 20990, 4727, 10663, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x9F08A88C3C5819970f9aeD8704A029dd443076A2/sources/contracts/workshop.sol
creates a new user and returns the reference to it
user storage new_user = employees.push();
1,874,081
[ 1, 19787, 279, 394, 729, 471, 1135, 326, 2114, 358, 518, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 729, 2502, 394, 67, 1355, 273, 24539, 25521, 18, 6206, 5621, 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 ]
// Sources flattened with hardhat v2.5.0 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/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; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File contracts/math/BitMath.sol pragma solidity 0.7.5; library BitMath { function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, "BitMath::mostSignificantBit: zero"); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } } // File contracts/math/FullMath.sol pragma solidity 0.7.5; library FullMath { function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; require(h < d, "FullMath::mulDiv: overflow"); return fullDiv(l, h, d); } } // File contracts/math/FixedPoint.sol pragma solidity 0.7.5; library Babylonian { function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a uq112x112 into a uint with 18 decimals of precision function decode112with18(uq112x112 memory self) internal pure returns (uint256) { return uint256(self._x) / 5192296858534827; } function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint::fraction: division by zero"); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), "FixedPoint::fraction: overflow"); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), "FixedPoint::fraction: overflow"); return uq112x112(uint224(result)); } } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112( uint224( Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2) ) ); } } // File contracts/BondingCalculator.sol pragma solidity 0.7.5; library MySafeMath { 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; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sqrrt(uint256 a) internal pure returns (uint256 c) { if (a > 3) { c = a; uint256 b = add(div(a, 2), 1); while (b < c) { c = b; b = div(add(div(a, b), b), 2); } } else if (a != 0) { c = 1; } } } interface IUniswapV2ERC20 { function totalSupply() external view returns (uint256); } interface IUniswapV2Pair is IUniswapV2ERC20 { function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function token0() external view returns (address); function token1() external view returns (address); } contract BondingCalculator { using FixedPoint for *; using MySafeMath for uint256; using MySafeMath for uint112; address public immutable HADES; constructor(address _HADES) { require(_HADES != address(0)); HADES = _HADES; } function getKValue(address _pair) public view returns (uint256 k_) { uint256 token0 = ERC20(IUniswapV2Pair(_pair).token0()).decimals(); uint256 token1 = ERC20(IUniswapV2Pair(_pair).token1()).decimals(); uint256 decimals = token0.add(token1).sub(ERC20(_pair).decimals()); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(_pair) .getReserves(); k_ = reserve0.mul(reserve1).div(10**decimals); } function getTotalValue(address _pair) public view returns (uint256 _value) { _value = getKValue(_pair).sqrrt().mul(2); } function valuation(address _pair, uint256 amount_) external view returns (uint256 _value) { uint256 totalValue = getTotalValue(_pair); uint256 totalSupply = IUniswapV2Pair(_pair).totalSupply(); _value = totalValue .mul(FixedPoint.fraction(amount_, totalSupply).decode112with18()) .div(1e18); } function markdown(address _pair) external view returns (uint256) { (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(_pair) .getReserves(); uint256 reserve; if (IUniswapV2Pair(_pair).token0() == HADES) { reserve = reserve1; } else { reserve = reserve0; } return reserve.mul(2 * (10**ERC20(HADES).decimals())).div(getTotalValue(_pair)); } } // File @openzeppelin/contracts/access/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view 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; } } // 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; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File @openzeppelin/contracts/access/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // File @openzeppelin/contracts/presets/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC20PresetMinterPauser is Context, AccessControl, ERC20Burnable, ERC20Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor(string memory name, string memory symbol) public ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } } // File contracts/Treasury.sol pragma solidity 0.7.5; contract Treasury is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; event Deposit(address indexed token, uint256 amount, uint256 value); event Withdrawal(address indexed token, uint256 amount, uint256 value); event CreateDebt( address indexed debtor, address indexed token, uint256 amount, uint256 value ); event RepayDebt( address indexed debtor, address indexed token, uint256 amount, uint256 value ); event ReservesManaged(address indexed token, uint256 amount); event ReservesUpdated(uint256 indexed totalReserves); event ReservesAudited(uint256 indexed totalReserves); event RewardsMinted( address indexed caller, address indexed recipient, uint256 amount ); event ChangeQueued(MANAGING indexed managing, address queued); event ChangeActivated( MANAGING indexed managing, address activated, bool result ); enum MANAGING { RESERVEDEPOSITOR, RESERVESPENDER, RESERVETOKEN, RESERVEMANAGER, LIQUIDITYDEPOSITOR, LIQUIDITYTOKEN, LIQUIDITYMANAGER, DEBTOR, REWARDMANAGER, SHADES } address public immutable HADES; uint256 public immutable blocksNeededForQueue; address[] public reserveTokens; // Push only, beware false-positives. mapping(address => bool) public isReserveToken; mapping(address => uint256) public reserveTokenQueue; // Delays changes to mapping. address[] public reserveDepositors; // Push only, beware false-positives. Only for viewing. mapping(address => bool) public isReserveDepositor; mapping(address => uint256) public reserveDepositorQueue; // Delays changes to mapping. address[] public reserveSpenders; // Push only, beware false-positives. Only for viewing. mapping(address => bool) public isReserveSpender; mapping(address => uint256) public reserveSpenderQueue; // Delays changes to mapping. address[] public liquidityTokens; // Push only, beware false-positives. mapping(address => bool) public isLiquidityToken; mapping(address => uint256) public LiquidityTokenQueue; // Delays changes to mapping. address[] public liquidityDepositors; // Push only, beware false-positives. Only for viewing. mapping(address => bool) public isLiquidityDepositor; mapping(address => uint256) public LiquidityDepositorQueue; // Delays changes to mapping. mapping(address => address) public bondCalculator; // bond calculator for liquidity token address[] public reserveManagers; // Push only, beware false-positives. Only for viewing. mapping(address => bool) public isReserveManager; mapping(address => uint256) public ReserveManagerQueue; // Delays changes to mapping. address[] public liquidityManagers; // Push only, beware false-positives. Only for viewing. mapping(address => bool) public isLiquidityManager; mapping(address => uint256) public LiquidityManagerQueue; // Delays changes to mapping. address[] public debtors; // Push only, beware false-positives. Only for viewing. mapping(address => bool) public isDebtor; mapping(address => uint256) public debtorQueue; // Delays changes to mapping. mapping(address => uint256) public debtorBalance; address[] public rewardManagers; // Push only, beware false-positives. Only for viewing. mapping(address => bool) public isRewardManager; mapping(address => uint256) public rewardManagerQueue; // Delays changes to mapping. address public sHADES; uint256 public sHADESQueue; // Delays change to sHADES address uint256 public totalReserves; // Risk-free value of all assets uint256 public totalDebt; constructor( address _HADES, address _OHM, uint256 _blocksNeededForQueue ) { require(_HADES != address(0)); HADES = _HADES; isReserveToken[_OHM] = true; reserveTokens.push(_OHM); blocksNeededForQueue = _blocksNeededForQueue; } /** @notice allow approved address to deposit an asset for HADES @param _amount uint @param _token address @param _profit uint @param _only_deposit bool @return send_ uint */ function deposit( uint256 _amount, address _token, uint256 _profit, bool _only_deposit ) external returns (uint256 send_) { require(isReserveToken[_token] || isLiquidityToken[_token], "Not accepted"); IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); if (isReserveToken[_token]) { require(isReserveDepositor[msg.sender], "Not approved"); } else { require(isLiquidityDepositor[msg.sender], "Not approved"); } uint256 value = valueOfToken(_token, _amount); // Just update reserves if _only_deposit is true - no HADES minting. // This is for sending the OHM from the aHades contract. // Otherwise, treat it like a normal deposit. if (_only_deposit) { totalReserves = totalReserves.add(value); emit ReservesUpdated(totalReserves); } else { // mint HADES needed and store amount of rewards for distribution send_ = value.sub(_profit); ERC20PresetMinterPauser(HADES).mint(msg.sender, send_); totalReserves = totalReserves.add(value); emit ReservesUpdated(totalReserves); emit Deposit(_token, _amount, value); } } /** @notice allow approved address to burn HADES for reserves @param _amount uint @param _token address */ function withdraw(uint256 _amount, address _token) external { require(isReserveToken[_token], "Not accepted"); // Only reserves can be used for redemptions require(isReserveSpender[msg.sender] == true, "Not approved"); uint256 value = valueOfToken(_token, _amount); ERC20PresetMinterPauser(HADES).burnFrom(msg.sender, value); totalReserves = totalReserves.sub(value); emit ReservesUpdated(totalReserves); IERC20(_token).safeTransfer(msg.sender, _amount); emit Withdrawal(_token, _amount, value); } /** @notice allow approved address to borrow reserves @param _amount uint @param _token address */ function incurDebt(uint256 _amount, address _token) external { require(isDebtor[msg.sender], "Not approved"); require(isReserveToken[_token], "Not accepted"); uint256 value = valueOfToken(_token, _amount); uint256 maximumDebt = IERC20(sHADES).balanceOf(msg.sender); // Can only borrow against sHADES held uint256 availableDebt = maximumDebt.sub(debtorBalance[msg.sender]); require(value <= availableDebt, "Exceeds debt limit"); debtorBalance[msg.sender] = debtorBalance[msg.sender].add(value); totalDebt = totalDebt.add(value); totalReserves = totalReserves.sub(value); emit ReservesUpdated(totalReserves); IERC20(_token).transfer(msg.sender, _amount); emit CreateDebt(msg.sender, _token, _amount, value); } /** @notice allow approved address to repay borrowed reserves with reserves @param _amount uint @param _token address */ function repayDebtWithReserve(uint256 _amount, address _token) external { require(isDebtor[msg.sender], "Not approved"); require(isReserveToken[_token], "Not accepted"); IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); uint256 value = valueOfToken(_token, _amount); debtorBalance[msg.sender] = debtorBalance[msg.sender].sub(value); totalDebt = totalDebt.sub(value); totalReserves = totalReserves.add(value); emit ReservesUpdated(totalReserves); emit RepayDebt(msg.sender, _token, _amount, value); } /** @notice allow approved address to repay borrowed reserves with HADES @param _amount uint */ function repayDebtWithHADES(uint256 _amount) external { require(isDebtor[msg.sender], "Not approved"); ERC20PresetMinterPauser(HADES).burnFrom(msg.sender, _amount); debtorBalance[msg.sender] = debtorBalance[msg.sender].sub(_amount); totalDebt = totalDebt.sub(_amount); emit RepayDebt(msg.sender, HADES, _amount, _amount); } /** @notice allow approved address to withdraw assets @param _token address @param _amount uint */ function manage(address _token, uint256 _amount) external { if (isLiquidityToken[_token]) { require(isLiquidityManager[msg.sender], "Not approved"); } else { require(isReserveManager[msg.sender], "Not approved"); } uint256 value = valueOfToken(_token, _amount); require(value <= excessReserves(), "Insufficient reserves"); totalReserves = totalReserves.sub(value); emit ReservesUpdated(totalReserves); IERC20(_token).safeTransfer(msg.sender, _amount); emit ReservesManaged(_token, _amount); } /** @notice send epoch reward to staking contract */ function mintRewards(address _recipient, uint256 _amount) external { require(isRewardManager[msg.sender], "Not approved"); require(_amount <= excessReserves(), "Insufficient reserves"); ERC20PresetMinterPauser(HADES).mint(_recipient, _amount); emit RewardsMinted(msg.sender, _recipient, _amount); } /** @notice returns excess reserves not backing tokens @return uint */ function excessReserves() public view returns (uint256) { return totalReserves.sub(IERC20(HADES).totalSupply().sub(totalDebt)); } /** @notice takes inventory of all tracked assets @notice always consolidate to recognized reserves before audit */ function auditReserves() external onlyOwner { uint256 reserves; for (uint256 i = 0; i < reserveTokens.length; i++) { reserves = reserves.add( valueOfToken( reserveTokens[i], IERC20(reserveTokens[i]).balanceOf(address(this)) ) ); } for (uint256 i = 0; i < liquidityTokens.length; i++) { reserves = reserves.add( valueOfToken( liquidityTokens[i], IERC20(liquidityTokens[i]).balanceOf(address(this)) ) ); } totalReserves = reserves; emit ReservesUpdated(reserves); emit ReservesAudited(reserves); } /** @notice returns HADES valuation of asset @param _token address @param _amount uint @return value_ uint */ function valueOfToken(address _token, uint256 _amount) public view returns (uint256 value_) { if (isReserveToken[_token]) { // convert amount to match HADES decimals value_ = _amount .mul(10**ERC20(HADES).decimals()) .div(10**ERC20(_token).decimals()); } else if (isLiquidityToken[_token]) { value_ = BondingCalculator(bondCalculator[_token]).valuation( _token, _amount ); } } /** @notice queue address to change boolean in mapping @param _managing MANAGING @param _address address @return bool */ function queue(MANAGING _managing, address _address) external onlyOwner returns (bool) { require(_address != address(0)); if (_managing == MANAGING.RESERVEDEPOSITOR) { // 0 reserveDepositorQueue[_address] = block.number.add(blocksNeededForQueue); } else if (_managing == MANAGING.RESERVESPENDER) { // 1 reserveSpenderQueue[_address] = block.number.add(blocksNeededForQueue); } else if (_managing == MANAGING.RESERVETOKEN) { // 2 reserveTokenQueue[_address] = block.number.add(blocksNeededForQueue); } else if (_managing == MANAGING.RESERVEMANAGER) { // 3 ReserveManagerQueue[_address] = block.number.add( blocksNeededForQueue.mul(2) ); } else if (_managing == MANAGING.LIQUIDITYDEPOSITOR) { // 4 LiquidityDepositorQueue[_address] = block.number.add( blocksNeededForQueue ); } else if (_managing == MANAGING.LIQUIDITYTOKEN) { // 5 LiquidityTokenQueue[_address] = block.number.add(blocksNeededForQueue); } else if (_managing == MANAGING.LIQUIDITYMANAGER) { // 6 LiquidityManagerQueue[_address] = block.number.add( blocksNeededForQueue.mul(2) ); } else if (_managing == MANAGING.DEBTOR) { // 7 debtorQueue[_address] = block.number.add(blocksNeededForQueue); } else if (_managing == MANAGING.REWARDMANAGER) { // 8 rewardManagerQueue[_address] = block.number.add(blocksNeededForQueue); } else if (_managing == MANAGING.SHADES) { // 9 sHADESQueue = block.number.add(blocksNeededForQueue); } else return false; emit ChangeQueued(_managing, _address); return true; } /** @notice verify queue then set boolean in mapping @param _managing MANAGING @param _address address @param _calculator address @return bool */ function toggle( MANAGING _managing, address _address, address _calculator ) external onlyOwner returns (bool) { require(_address != address(0)); bool result; if (_managing == MANAGING.RESERVEDEPOSITOR) { // 0 if (requirements(reserveDepositorQueue, isReserveDepositor, _address)) { reserveDepositorQueue[_address] = 0; if (!listContains(reserveDepositors, _address)) { reserveDepositors.push(_address); } } result = !isReserveDepositor[_address]; isReserveDepositor[_address] = result; } else if (_managing == MANAGING.RESERVESPENDER) { // 1 if (requirements(reserveSpenderQueue, isReserveSpender, _address)) { reserveSpenderQueue[_address] = 0; if (!listContains(reserveSpenders, _address)) { reserveSpenders.push(_address); } } result = !isReserveSpender[_address]; isReserveSpender[_address] = result; } else if (_managing == MANAGING.RESERVETOKEN) { // 2 if (requirements(reserveTokenQueue, isReserveToken, _address)) { reserveTokenQueue[_address] = 0; if (!listContains(reserveTokens, _address)) { reserveTokens.push(_address); } } result = !isReserveToken[_address]; isReserveToken[_address] = result; } else if (_managing == MANAGING.RESERVEMANAGER) { // 3 if (requirements(ReserveManagerQueue, isReserveManager, _address)) { reserveManagers.push(_address); ReserveManagerQueue[_address] = 0; if (!listContains(reserveManagers, _address)) { reserveManagers.push(_address); } } result = !isReserveManager[_address]; isReserveManager[_address] = result; } else if (_managing == MANAGING.LIQUIDITYDEPOSITOR) { // 4 if ( requirements(LiquidityDepositorQueue, isLiquidityDepositor, _address) ) { liquidityDepositors.push(_address); LiquidityDepositorQueue[_address] = 0; if (!listContains(liquidityDepositors, _address)) { liquidityDepositors.push(_address); } } result = !isLiquidityDepositor[_address]; isLiquidityDepositor[_address] = result; } else if (_managing == MANAGING.LIQUIDITYTOKEN) { // 5 if (requirements(LiquidityTokenQueue, isLiquidityToken, _address)) { LiquidityTokenQueue[_address] = 0; if (!listContains(liquidityTokens, _address)) { liquidityTokens.push(_address); } } result = !isLiquidityToken[_address]; isLiquidityToken[_address] = result; bondCalculator[_address] = _calculator; } else if (_managing == MANAGING.LIQUIDITYMANAGER) { // 6 if (requirements(LiquidityManagerQueue, isLiquidityManager, _address)) { LiquidityManagerQueue[_address] = 0; if (!listContains(liquidityManagers, _address)) { liquidityManagers.push(_address); } } result = !isLiquidityManager[_address]; isLiquidityManager[_address] = result; } else if (_managing == MANAGING.DEBTOR) { // 7 if (requirements(debtorQueue, isDebtor, _address)) { debtorQueue[_address] = 0; if (!listContains(debtors, _address)) { debtors.push(_address); } } result = !isDebtor[_address]; isDebtor[_address] = result; } else if (_managing == MANAGING.REWARDMANAGER) { // 8 if (requirements(rewardManagerQueue, isRewardManager, _address)) { rewardManagerQueue[_address] = 0; if (!listContains(rewardManagers, _address)) { rewardManagers.push(_address); } } result = !isRewardManager[_address]; isRewardManager[_address] = result; } else if (_managing == MANAGING.SHADES) { // 9 sHADESQueue = 0; sHADES = _address; result = true; } else return false; emit ChangeActivated(_managing, _address, result); return true; } /** @notice checks requirements and returns altered structs @param queue_ mapping( address => uint256 ) @param status_ mapping( address => bool ) @param _address address @return bool */ function requirements( mapping(address => uint256) storage queue_, mapping(address => bool) storage status_, address _address ) internal view returns (bool) { if (!status_[_address]) { require(queue_[_address] != 0, "Must queue"); require(queue_[_address] <= block.number, "Queue not expired"); return true; } return false; } /** @notice checks array to ensure against duplicate @param _list address[] @param _token address @return bool */ function listContains(address[] storage _list, address _token) internal view returns (bool) { for (uint256 i = 0; i < _list.length; i++) { if (_list[i] == _token) { return true; } } return false; } } // File contracts/Distributor.sol pragma solidity 0.7.5; contract Distributor is Ownable { using SafeMath for uint256; /* ====== VARIABLES ====== */ address public immutable HADES; address public immutable treasury; uint256 public immutable epochLength; uint256 public nextEpochBlock; mapping(uint256 => Adjust) public adjustments; /* ====== STRUCTS ====== */ struct Info { uint256 rate; // in ten-thousandths ( 5000 = 0.5% ) address recipient; } Info[] public info; struct Adjust { bool add; uint256 rate; uint256 target; } /* ====== CONSTRUCTOR ====== */ constructor( address _treasury, address _hades, uint256 _epochLength, uint256 _nextEpochBlock ) { require(_treasury != address(0)); treasury = _treasury; require(_hades != address(0)); HADES = _hades; epochLength = _epochLength; nextEpochBlock = _nextEpochBlock; } /* ====== PUBLIC FUNCTIONS ====== */ /** @notice send epoch reward to staking contract */ function distribute() external returns (bool) { if (nextEpochBlock <= block.number) { nextEpochBlock = nextEpochBlock.add(epochLength); // set next epoch block // distribute rewards to each recipient for (uint256 i = 0; i < info.length; i++) { if (info[i].rate > 0) { Treasury(treasury).mintRewards( // mint and send from treasury info[i].recipient, nextRewardAt(info[i].rate) ); adjust(i); // check for adjustment } } return true; } else { return false; } } /* ====== INTERNAL FUNCTIONS ====== */ /** @notice increment reward rate for collector */ function adjust(uint256 _index) internal { Adjust memory adjustment = adjustments[_index]; if (adjustment.rate != 0) { if (adjustment.add) { // if rate should increase info[_index].rate = info[_index].rate.add(adjustment.rate); // raise rate if (info[_index].rate >= adjustment.target) { // if target met adjustments[_index].rate = 0; // turn off adjustment } } else { // if rate should decrease info[_index].rate = info[_index].rate.sub(adjustment.rate); // lower rate if (info[_index].rate <= adjustment.target) { // if target met adjustments[_index].rate = 0; // turn off adjustment } } } } /* ====== VIEW FUNCTIONS ====== */ /** @notice view function for next reward at given rate @param _rate uint @return uint */ function nextRewardAt(uint256 _rate) public view returns (uint256) { return IERC20(HADES).totalSupply().mul(_rate).div(1000000); } /** @notice view function for next reward for specified address @param _recipient address @return uint */ function nextRewardFor(address _recipient) public view returns (uint256) { uint256 reward; for (uint256 i = 0; i < info.length; i++) { if (info[i].recipient == _recipient) { reward = nextRewardAt(info[i].rate); } } return reward; } /* ====== POLICY FUNCTIONS ====== */ /** @notice adds recipient for distributions @param _recipient address @param _rewardRate uint */ function addRecipient(address _recipient, uint256 _rewardRate) external onlyOwner { require(_recipient != address(0)); info.push(Info({recipient: _recipient, rate: _rewardRate})); } /** @notice removes recipient for distributions @param _index uint @param _recipient address */ function removeRecipient(uint256 _index, address _recipient) external onlyOwner { require(_recipient == info[_index].recipient); info[_index].recipient = address(0); info[_index].rate = 0; } /** @notice set adjustment info for a collector's reward rate @param _index uint @param _add bool @param _rate uint @param _target uint */ function setAdjustment( uint256 _index, bool _add, uint256 _rate, uint256 _target ) external onlyOwner { adjustments[_index] = Adjust({add: _add, rate: _rate, target: _target}); } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File contracts/sHades.sol pragma solidity 0.7.5; interface sHadesIERC20 { /** * @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); } abstract contract sHadesERC20 is sHadesIERC20 { using SafeMath for uint256; // TODO comment actual hash value. bytes32 private constant ERC20TOKEN_ERC1820_INTERFACE_ID = keccak256("ERC20Token"); // Present in ERC777 mapping(address => uint256) internal _balances; // Present in ERC777 mapping(address => mapping(address => uint256)) internal _allowances; // Present in ERC777 uint256 internal _totalSupply; // Present in ERC777 string internal _name; // Present in ERC777 string internal _symbol; // Present in ERC777 uint8 internal _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_, uint8 decimals_ ) { _name = name_; _symbol = symbol_; _decimals = decimals_; } /** * @dev Returns the name of the token. */ // Present in ERC777 function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ // Present in ERC777 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}. */ // Present in ERC777 function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ // Present in ERC777 function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ // Present in ERC777 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`. */ // Overrideen in ERC777 // Confirm that this behavior changes function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ // Present in ERC777 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. */ // Present in ERC777 function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, 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`. */ // Present in ERC777 function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _allowances[sender][msg.sender].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( msg.sender, spender, _allowances[msg.sender][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][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. */ // Present in ERC777 function _mint(address account_, uint256 ammount_) internal virtual { require(account_ != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(this), account_, ammount_); _totalSupply = _totalSupply.add(ammount_); _balances[account_] = _balances[account_].add(ammount_); emit Transfer(address(this), account_, ammount_); } /** * @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. */ // Present in ERC777 function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ // Present in ERC777 function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ // Considering deprication to reduce size of bytecode as changing _decimals to internal acheived the same functionality. // function _setupDecimals(uint8 decimals_) internal { // _decimals = decimals_; // } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ // Present in ERC777 function _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) internal virtual {} } interface IERC2612Permit { /** * @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current ERC2612 nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); } abstract contract ERC20Permit is sHadesERC20, IERC2612Permit { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; bytes32 public DOMAIN_SEPARATOR; constructor() { uint256 chainID; assembly { chainID := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name())), keccak256(bytes("1")), // Version chainID, address(this) ) ); } /** * @dev See {IERC2612Permit-permit}. * */ function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "Permit: expired deadline"); bytes32 hashStruct = keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline ) ); bytes32 _hash = keccak256( abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct) ); address signer = ecrecover(_hash, v, r, s); require( signer != address(0) && signer == owner, "ZeroSwapPermit: Invalid signature" ); _nonces[owner].increment(); _approve(owner, spender, amount); } /** * @dev See {IERC2612Permit-nonces}. */ function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } } contract sHades is ERC20Permit, Ownable { using SafeMath for uint256; modifier onlyStakingContract() { require(msg.sender == stakingContract); _; } address public stakingContract; address public initializer; event LogSupply( uint256 indexed epoch, uint256 timestamp, uint256 totalSupply ); event LogRebase(uint256 indexed epoch, uint256 rebase, uint256 index); event LogStakingContractUpdated(address stakingContract); struct Rebase { uint256 epoch; uint256 rebase; // 18 decimals uint256 totalStakedBefore; uint256 totalStakedAfter; uint256 amountRebased; uint256 index; uint256 blockNumberOccured; } Rebase[] public rebases; uint256 public INDEX; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 5000000 * 10**9; // TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer. // Use the highest value that fits in a uint256 for max granularity. uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY); // MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2 uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _gonsPerFragment; mapping(address => uint256) private _gonBalances; mapping(address => mapping(address => uint256)) private _allowedValue; constructor() sHadesERC20("Staked Hades", "sHADES", 9) ERC20Permit() { initializer = msg.sender; _totalSupply = INITIAL_FRAGMENTS_SUPPLY; _gonsPerFragment = TOTAL_GONS.div(_totalSupply); } function initialize(address stakingContract_) external returns (bool) { require(msg.sender == initializer); require(stakingContract_ != address(0)); stakingContract = stakingContract_; _gonBalances[stakingContract] = TOTAL_GONS; emit Transfer(address(0x0), stakingContract, _totalSupply); emit LogStakingContractUpdated(stakingContract_); initializer = address(0); return true; } function setIndex(uint256 _INDEX) external onlyOwner returns (bool) { require(INDEX == 0); INDEX = gonsForBalance(_INDEX); return true; } /** @notice increases sOHM supply to increase staking balances relative to profit_ @param profit_ uint256 @return uint256 */ function rebase(uint256 profit_, uint256 epoch_) public onlyStakingContract returns (uint256) { uint256 rebaseAmount; uint256 circulatingSupply_ = circulatingSupply(); if (profit_ == 0) { emit LogSupply(epoch_, block.timestamp, _totalSupply); emit LogRebase(epoch_, 0, index()); return _totalSupply; } else if (circulatingSupply_ > 0) { rebaseAmount = profit_.mul(_totalSupply).div(circulatingSupply_); } else { rebaseAmount = profit_; } _totalSupply = _totalSupply.add(rebaseAmount); if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _gonsPerFragment = TOTAL_GONS.div(_totalSupply); _storeRebase(circulatingSupply_, profit_, epoch_); return _totalSupply; } /** @notice emits event with data about rebase @param previousCirculating_ uint @param profit_ uint @param epoch_ uint @return bool */ function _storeRebase( uint256 previousCirculating_, uint256 profit_, uint256 epoch_ ) internal returns (bool) { uint256 rebasePercent = profit_.mul(1e18).div(previousCirculating_); rebases.push( Rebase({ epoch: epoch_, rebase: rebasePercent, // 18 decimals totalStakedBefore: previousCirculating_, totalStakedAfter: circulatingSupply(), amountRebased: profit_, index: index(), blockNumberOccured: block.number }) ); emit LogSupply(epoch_, block.timestamp, _totalSupply); emit LogRebase(epoch_, rebasePercent, index()); return true; } function balanceOf(address who) public view override returns (uint256) { return _gonBalances[who].div(_gonsPerFragment); } function gonsForBalance(uint256 amount) public view returns (uint256) { return amount.mul(_gonsPerFragment); } function balanceForGons(uint256 gons) public view returns (uint256) { return gons.div(_gonsPerFragment); } // Staking contract holds excess sOHM function circulatingSupply() public view returns (uint256) { return _totalSupply.sub(balanceOf(stakingContract)); } function index() public view returns (uint256) { return balanceForGons(INDEX); } function transfer(address to, uint256 value) public override returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue); _gonBalances[to] = _gonBalances[to].add(gonValue); emit Transfer(msg.sender, to, value); return true; } function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedValue[owner_][spender]; } function transferFrom( address from, address to, uint256 value ) public override returns (bool) { _allowedValue[from][msg.sender] = _allowedValue[from][msg.sender].sub( value ); emit Approval(from, msg.sender, _allowedValue[from][msg.sender]); uint256 gonValue = gonsForBalance(value); _gonBalances[from] = _gonBalances[from].sub(gonValue); _gonBalances[to] = _gonBalances[to].add(gonValue); emit Transfer(from, to, value); return true; } function approve(address spender, uint256 value) public override returns (bool) { _allowedValue[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } // What gets called in a permit function _approve( address owner, address spender, uint256 value ) internal virtual override { _allowedValue[owner][spender] = value; emit Approval(owner, spender, value); } function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) { _allowedValue[msg.sender][spender] = _allowedValue[msg.sender][spender].add( addedValue ); emit Approval(msg.sender, spender, _allowedValue[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) { uint256 oldValue = _allowedValue[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedValue[msg.sender][spender] = 0; } else { _allowedValue[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedValue[msg.sender][spender]); return true; } } // File contracts/StakingWarmup.sol pragma solidity 0.7.5; contract StakingWarmup { address public immutable staking; address public immutable sHADES; constructor(address _staking, address _sHADES) { require(_staking != address(0)); staking = _staking; require(_sHADES != address(0)); sHADES = _sHADES; } function retrieve(address _staker, uint256 _amount) external { require(msg.sender == staking); IERC20(sHADES).transfer(_staker, _amount); } } // File contracts/Staking.sol pragma solidity 0.7.5; contract Staking is Ownable { using SafeMath for uint256; address public immutable HADES; address public immutable sHADES; struct Epoch { uint256 length; uint256 number; uint256 endBlock; uint256 distribute; } Epoch public epoch; address public distributor; address public locker; uint256 public totalBonus; address public warmupContract; uint256 public warmupPeriod; constructor( address _HADES, address _sHADES, uint256 _epochLength, uint256 _firstEpochNumber, uint256 _firstEpochBlock ) { require(_HADES != address(0)); HADES = _HADES; require(_sHADES != address(0)); sHADES = _sHADES; epoch = Epoch({ length: _epochLength, number: _firstEpochNumber, endBlock: _firstEpochBlock, distribute: 0 }); } struct Claim { uint256 deposit; uint256 gons; uint256 expiry; bool lock; // prevents malicious delays } mapping(address => Claim) public warmupInfo; /** @notice stake HADES to enter warmup @param _amount uint @return bool */ function stake(uint256 _amount, address _recipient) external returns (bool) { rebase(); SafeERC20.safeTransferFrom( IERC20(HADES), msg.sender, address(this), _amount ); Claim memory info = warmupInfo[_recipient]; require(!info.lock, "Deposits for account are locked"); warmupInfo[_recipient] = Claim({ deposit: info.deposit.add(_amount), gons: info.gons.add(sHades(sHADES).gonsForBalance(_amount)), expiry: epoch.number.add(warmupPeriod), lock: false }); SafeERC20.safeTransfer(IERC20(sHADES), warmupContract, _amount); return true; } /** @notice retrieve sHADES from warmup @param _recipient address */ function claim(address _recipient) public { Claim memory info = warmupInfo[_recipient]; if (epoch.number >= info.expiry && info.expiry != 0) { delete warmupInfo[_recipient]; StakingWarmup(warmupContract).retrieve( _recipient, sHades(sHADES).balanceForGons(info.gons) ); } } /** @notice forfeit sHADES in warmup and retrieve HADES */ function forfeit() external { Claim memory info = warmupInfo[msg.sender]; delete warmupInfo[msg.sender]; StakingWarmup(warmupContract).retrieve( address(this), sHades(sHADES).balanceForGons(info.gons) ); SafeERC20.safeTransfer(IERC20(HADES), msg.sender, info.deposit); } /** @notice prevent new deposits to address (protection from malicious activity) */ function toggleDepositLock() external { warmupInfo[msg.sender].lock = !warmupInfo[msg.sender].lock; } /** @notice redeem sHADES for HADES @param _amount uint @param _trigger bool */ function unstake(uint256 _amount, bool _trigger) external { if (_trigger) { rebase(); } SafeERC20.safeTransferFrom( IERC20(sHADES), msg.sender, address(this), _amount ); SafeERC20.safeTransfer(IERC20(HADES), msg.sender, _amount); } /** @notice returns the sHADES index, which tracks rebase growth @return uint */ function index() public view returns (uint256) { return sHades(sHADES).index(); } /** @notice trigger rebase if epoch over */ function rebase() public { if (epoch.endBlock <= block.number) { sHades(sHADES).rebase(epoch.distribute, epoch.number); epoch.endBlock = epoch.endBlock.add(epoch.length); epoch.number++; if (distributor != address(0)) { Distributor(distributor).distribute(); } uint256 balance = contractBalance(); uint256 staked = sHades(sHADES).circulatingSupply(); if (balance <= staked) { epoch.distribute = 0; } else { epoch.distribute = balance.sub(staked); } } } /** @notice returns contract HADES holdings, including bonuses provided @return uint */ function contractBalance() public view returns (uint256) { return IERC20(HADES).balanceOf(address(this)).add(totalBonus); } /** @notice provide bonus to locked staking contract @param _amount uint */ function giveLockBonus(uint256 _amount) external { require(msg.sender == locker); totalBonus = totalBonus.add(_amount); SafeERC20.safeTransfer(IERC20(sHADES), locker, _amount); } /** @notice reclaim bonus from locked staking contract @param _amount uint */ function returnLockBonus(uint256 _amount) external { require(msg.sender == locker); totalBonus = totalBonus.sub(_amount); SafeERC20.safeTransferFrom(IERC20(sHADES), locker, address(this), _amount); } enum CONTRACTS { DISTRIBUTOR, WARMUP, LOCKER } /** @notice sets the contract address for LP staking @param _contract address */ function setContract(CONTRACTS _contract, address _address) external onlyOwner { if (_contract == CONTRACTS.DISTRIBUTOR) { // 0 distributor = _address; } else if (_contract == CONTRACTS.WARMUP) { // 1 require( warmupContract == address(0), "Warmup cannot be set more than once" ); warmupContract = _address; } else if (_contract == CONTRACTS.LOCKER) { // 2 require(locker == address(0), "Locker cannot be set more than once"); locker = _address; } } /** * @notice set warmup period for new stakers * @param _warmupPeriod uint */ function setWarmup(uint256 _warmupPeriod) external onlyOwner { warmupPeriod = _warmupPeriod; } } // File contracts/StakingHelper.sol pragma solidity 0.7.5; contract StakingHelper { address public immutable staking; address public immutable HADES; constructor(address _staking, address _HADES) { require(_staking != address(0)); staking = _staking; require(_HADES != address(0)); HADES = _HADES; } function stake(uint256 _amount, address _recipient) external { IERC20(HADES).transferFrom(msg.sender, address(this), _amount); IERC20(HADES).approve(staking, _amount); Staking(staking).stake(_amount, _recipient); Staking(staking).claim(_recipient); } }
Push only, beware false-positives.
address[] public liquidityTokens;
283,122
[ 1, 7621, 1338, 16, 324, 359, 834, 629, 17, 1724, 3606, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 1758, 8526, 1071, 4501, 372, 24237, 5157, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.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)); } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view 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()); } } /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC20PresetMinterPauser is Context, AccessControl, ERC20Burnable, ERC20Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor(string memory name, string memory symbol) ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } }
* @dev Returns the number of accounts that have `role`. Can be used together with {getRoleMember} to enumerate all bearers of a role./
function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); }
14,658,080
[ 1, 1356, 326, 1300, 434, 9484, 716, 1240, 1375, 4615, 8338, 4480, 506, 1399, 9475, 598, 288, 588, 2996, 4419, 97, 358, 4241, 777, 506, 297, 414, 434, 279, 2478, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 15673, 4419, 1380, 12, 3890, 1578, 2478, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 7774, 63, 4615, 8009, 7640, 18, 2469, 5621, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x2e4c311BbD6e2E65Bd7b0167a3d71F9cc924B112/sources/IbETHRouter.sol
returns sorted token addresses, used to handle return values from pairs sorted in this order
library UniswapV2Library { using SafeMath for uint256; function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } function pairFor( address factory, address tokenA, address tokenB ) internal view returns (address pair) { } function getReserves( address factory, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } function getAmountsOut( address factory, uint256 amountIn, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } function getAmountsOut( address factory, uint256 amountIn, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } function getAmountsIn( address factory, uint256 amountOut, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } function getAmountsIn( address factory, uint256 amountOut, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } }
5,121,502
[ 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, 1351, 291, 91, 438, 58, 22, 9313, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 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, 984, 291, 91, 438, 58, 22, 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, 984, 291, 91, 438, 58, 22, 9313, 30, 18449, 67, 15140, 8284, 203, 565, 289, 203, 203, 565, 445, 3082, 1290, 12, 203, 3639, 1758, 3272, 16, 203, 3639, 1758, 1147, 37, 16, 203, 3639, 1758, 1147, 38, 203, 565, 262, 2713, 1476, 1135, 261, 2867, 3082, 13, 288, 203, 565, 289, 203, 203, 565, 445, 31792, 264, 3324, 12, 203, 3639, 1758, 3272, 16, 203, 3639, 1758, 1147, 37, 16, 203, 3639, 1758, 1147, 38, 203, 565, 262, 2713, 1476, 1135, 261, 11890, 5034, 20501, 37, 16, 2254, 5034, 20501, 38, 13, 288, 203, 3639, 261, 2867, 1147, 20, 16, 262, 273, 1524, 5157, 12, 2316, 37, 16, 1147, 38, 1769, 203, 3639, 261, 11890, 5034, 20501, 20, 16, 2254, 5034, 20501, 21, 16, 262, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 6017, 1290, 2 ]
./partial_match/1/0x74b57883f8ce9F2BD330286E884CfD8BB24AC4ED/sources/contracts/agreements/ConstantFlowAgreementV1.sol
NOTE because we are upcasting from type(uint96).max to uint256 to int256, we do not need to use safecast
function _clipDepositNumberRoundingDown(uint256 deposit) internal pure returns(uint256) } function _clipDepositNumberRoundingUp(uint256 deposit) internal pure returns(uint256) } function _calculateDeposit( int96 flowRate, uint256 liquidationPeriod ) internal pure returns(uint256 deposit) } } function _encodeFlowData ( FlowData memory flowData ) internal pure returns(bytes32[] memory data) } function _decodeFlowData ( uint256 wordA ) internal pure returns(bool exist, FlowData memory flowData) if (exist) { flowData.timestamp = uint32(wordA >> 224); flowData.flowRate = int96(int256(wordA >> 128) & int256(uint256(type(uint96).max))); flowData.deposit = ((wordA >> 64) & uint256(type(uint64).max)) << 32 /* recover clipped bits*/; flowData.owedDeposit = (wordA & uint256(type(uint64).max)) << 32 /* recover clipped bits*/; }
2,601,351
[ 1, 17857, 2724, 732, 854, 731, 4155, 310, 628, 618, 12, 11890, 10525, 2934, 1896, 358, 2254, 5034, 358, 509, 5034, 16, 732, 741, 486, 1608, 358, 999, 11029, 557, 689, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 14161, 758, 1724, 1854, 11066, 310, 4164, 12, 11890, 5034, 443, 1724, 13, 203, 3639, 2713, 16618, 203, 3639, 1135, 12, 11890, 5034, 13, 203, 565, 289, 203, 203, 565, 445, 389, 14161, 758, 1724, 1854, 11066, 310, 1211, 12, 11890, 5034, 443, 1724, 13, 203, 3639, 2713, 16618, 203, 3639, 1135, 12, 11890, 5034, 13, 203, 565, 289, 203, 203, 565, 445, 389, 11162, 758, 1724, 12, 203, 3639, 509, 10525, 4693, 4727, 16, 203, 3639, 2254, 5034, 4501, 26595, 367, 5027, 203, 565, 262, 203, 3639, 2713, 16618, 203, 3639, 1135, 12, 11890, 5034, 443, 1724, 13, 203, 565, 289, 203, 203, 203, 565, 289, 203, 203, 203, 565, 445, 389, 3015, 5249, 751, 203, 565, 261, 203, 3639, 9473, 751, 3778, 4693, 751, 203, 565, 262, 203, 3639, 2713, 16618, 203, 3639, 1135, 12, 3890, 1578, 8526, 3778, 501, 13, 203, 565, 289, 203, 203, 565, 445, 389, 3922, 5249, 751, 203, 565, 261, 203, 3639, 2254, 5034, 2076, 37, 203, 565, 262, 203, 3639, 2713, 16618, 203, 3639, 1135, 12, 6430, 1005, 16, 9473, 751, 3778, 4693, 751, 13, 203, 3639, 309, 261, 7398, 13, 288, 203, 5411, 4693, 751, 18, 5508, 273, 2254, 1578, 12, 1095, 37, 1671, 576, 3247, 1769, 203, 5411, 4693, 751, 18, 2426, 4727, 273, 509, 10525, 12, 474, 5034, 12, 1095, 37, 1671, 8038, 13, 473, 509, 5034, 12, 11890, 5034, 12, 723, 12, 11890, 10525, 2934, 1896, 3719, 1769, 203, 5411, 4693, 751, 18, 323, 1724, 273, 14015, 1095, 37, 2 ]
pragma solidity >=0.8.0 <0.9.0; //SPDX-License-Identifier: MIT import 'hardhat/console.sol'; //import "@openzeppelin/contracts/access/Ownable.sol"; //https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol contract YourContract { string public purpose = 'Building Unstoppable Apps!!!'; // this is an error handler //error EmptyPurposeError(uint code, string message); constructor() { // what should we do on deploy? } // this is an event for the function below event SetPurpose(address sender, string purpose); function setPurpose(string memory newPurpose) public payable { // you can add error handling! // if(bytes(newPurpose).length == 0){ // revert EmptyPurposeError({ // code: 1, // message: "Purpose can not be empty" // }); // } purpose = newPurpose; console.log(msg.sender, 'set purpose to', purpose); emit SetPurpose(msg.sender, purpose); } }
this is an event for the function below
event SetPurpose(address sender, string purpose);
948,975
[ 1, 2211, 353, 392, 871, 364, 326, 445, 5712, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 871, 1000, 10262, 4150, 12, 2867, 5793, 16, 533, 13115, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "./AccessAccount.sol"; contract TrustAccount is AccessAccount { //array of all the owner addresses address[] owners; //counter of all owners uint noOfOwners = 0; //ballot counter uint ballotIDs = 0; //the different types of votes enum VoteType {removeOwner, addOwner, changeOwner, withdrawRequest} //votes, containingthe voter, their vote and the ballot ID struct Vote { address voter; bool vote; uint ballotID; } //the owners, containing if they are active and all their votes struct OwnerDetails { bool isOwner; address ownerWallet; // Votes[] allVotes; } //the ballots, containing the votes specific details and an ID struct Ballot { uint ballotID; VoteType typeOfVote; uint startTime; uint endTime; address currentAddress; address newAddress; uint amount; bool actedOn; bool bankVoted; bool banksVote; } //ballots to their ids //change to array mapping(uint => Ballot) allBallots; //all votes for the ballot mapping(uint => Vote[]) allVotesForBallot; //user keys to their details mapping(uint => OwnerDetails) allOwners; //user addresses to keys mapping(address => uint) ownersKeys; event LogCreatedTrustAccount(address[] owners, address _bank, uint _limit); /** * @dev modifier checks that only the owner may call the function */ modifier isOwner() { if(msg.sender == bankAddress){ } else { uint key = ownersKeys[msg.sender]; require(allOwners[key].ownerWallet == msg.sender, "Address is not owner of Key"); require(allOwners[key].isOwner == true, "Function only accessible by owner"); } _; } /** * @dev the constructor sets the owner in the access account to the bank as * all the owners need equal status and replacability. */ constructor(address[] _owners, uint _limit) AccessAccount(msg.sender, AccessAccount.AccountType.trust, _limit) public { AccessAccount.onwerAddress = msg.sender; bankAddress = msg.sender; AccessAccount.accountLimit = _limit; uint noOfOwnersInArray = _owners.length; for(uint i = 0; i < noOfOwnersInArray; i++){ ownersKeys[_owners[i]] = i; allOwners[i] = OwnerDetails({ isOwner: true, ownerWallet: _owners[i] }); noOfOwners++; } emit LogCreatedTrustAccount(_owners, msg.sender, _limit); } /** * @param _ballotID : the ballots ID * @dev returns the details fo a single ballot */ function getBallot(uint _ballotID) public view returns( VoteType typeOfVote, uint startTime, uint endTime, address currentAddress, address newAddress, bool actedOn, bool bankVoted, bool banksVote ) { typeOfVote = allBallots[_ballotID].typeOfVote; startTime = allBallots[_ballotID].startTime; endTime = allBallots[_ballotID].endTime; currentAddress = allBallots[_ballotID].currentAddress; newAddress = allBallots[_ballotID].newAddress; actedOn = allBallots[_ballotID].actedOn; bankVoted = allBallots[_ballotID].bankVoted; banksVote = allBallots[_ballotID].banksVote; } /** * @dev returns all the owners of the trust account */ function getOwners() public view isOwner() returns(address[]) { return owners; } /** * @param _voteType : the type of vote it is * @param _current : if it is removing / changing / adding an owner: * if removing, this is the address of the owner to remove. * if changing, _current is their current address. * if adding an owner, current will be blank * if withdraw requset, this is the address the funds will be sent to * @param _new :if changing / adding an owner: * if changing, this will be their new address * if adding, contains the new address * if withdraw request then this is blank * @dev if the vote type is rejecting a withdraw requset then both addresses are empty */ function createBallot(VoteType _voteType, address _current, address _new, uint _amount) private returns(uint newBallotID) { if( _voteType == VoteType.removeOwner || _voteType == VoteType.addOwner || _voteType == VoteType.changeOwner ){ //vote is owners modification allBallots[ballotIDs] = Ballot({ ballotID: ballotIDs, typeOfVote: _voteType, startTime: now, //3 (days) x 24 (hours) x 60 (minutes) x 60 (secounds) = 259 200 endTime: now + 259200, currentAddress: _current, newAddress: _new, amount: 0, actedOn: false, bankVoted: false, banksVote: false }); newBallotID = ballotIDs; ballotIDs++; } else { //vote is rejecting withdraw. allBallots[ballotIDs] = Ballot({ ballotID: ballotIDs, typeOfVote: _voteType, startTime: now, endTime: now + 259200, currentAddress: _current, newAddress: 0x0, amount: _amount, actedOn: false, bankVoted: false, banksVote: false }); newBallotID = ballotIDs; ballotIDs++; } return newBallotID; } /** * @param _ballotID : the ballot ID * @param _vote : their vote for the ballot */ function voteFor(uint _ballotID, bool _vote) public isOwner() { if(msg.sender == AccessAccount.bankAddress){ if(_vote){ allBallots[_ballotID].bankVoted = true; allBallots[_ballotID].banksVote = true; } else { allBallots[_ballotID].bankVoted = true; allBallots[_ballotID].banksVote = false; } } else { require(allBallots[_ballotID].startTime > 0); require(allBallots[_ballotID].startTime <= now && allBallots[_ballotID].endTime > now); allVotesForBallot[_ballotID].push(Vote ({ voter: msg.sender, vote: _vote, ballotID: _ballotID })); } } /** * @param _to : the account to send the funds to * @param _amount : the amount to be withdrawn * @dev this allows owners to request withdraws */ function requestWithdraw(address _to, uint _amount) public isOwner() isFrozen() { AccessAccount.freeze(); require(_amount < balance, "Cannot withdraw more than owned"); createBallot(VoteType.withdrawRequest, _to, 0x0, _amount); AccessAccount.defrost(); } event LogBallotID(uint _ballotID); /** * @param _current : the current address of the owner * @param _new : the new address of the owner * @dev this is how owners can request to change their address * @notice the other owners will vote on this. If the vote dose * not pass the request will fail and will not be able to be acted on. */ function requestChangeOwnerAddress(address _current, address _new) public isOwner() isFrozen() returns(uint) { AccessAccount.freeze(); require(allOwners[ownersKeys[_current]].isOwner, "Current address not recognised"); uint ballotID = createBallot(VoteType.changeOwner, _current, _new, 0); AccessAccount.defrost(); emit LogBallotID(ballotID); return ballotID; } /** * @param _new : the address of the new owner * @dev this is where an existing owner can request to add * a new owner. * @notice This will be voted for by the other owners, * and if it fails the request will not be able to be acted on. */ function addOwnerRequest(address _new) public isOwner() isFrozen() { AccessAccount.freeze(); createBallot(VoteType.addOwner, 0x0, _new, 0); AccessAccount.defrost(); } /** * @param _toRemove : the address of the owner * @dev this allows owners to vote out fellow owners. * @notice Owners can vote out other owners. */ function removeOwnerRequest(address _toRemove) public isOwner() isFrozen() { AccessAccount.freeze(); require(allOwners[ownersKeys[_toRemove]].isOwner, "Owner has already been removed"); createBallot(VoteType.removeOwner, _toRemove, 0x0, 0); AccessAccount.defrost(); } /** * @param _ballotID : the number of the ballot ID to check * @dev this function checks that the vote has passed, (2/3 majority) * and that the ballot end time has passed */ function votePassed(uint _ballotID) private returns(bool) { if(allBallots[_ballotID].bankVoted){ allBallots[_ballotID].actedOn = true; if(allBallots[_ballotID].banksVote) return true; else return false; } else { require(allBallots[_ballotID].endTime < now, "Voting time has not ended. Please try again later"); require(allBallots[_ballotID].actedOn == false, "Withdraw has already taken place"); allBallots[_ballotID].actedOn = true; require(allVotesForBallot[_ballotID].length > 0); uint trueVotes = 0; uint falseVotes = 0; for(uint i = 0; i < allVotesForBallot[_ballotID].length; i++){ if(allVotesForBallot[_ballotID][i].vote) trueVotes++; else falseVotes++; } //if it ties it fails if(trueVotes > falseVotes) return true; else return false; } } /** * @param _ballotID : the ballots ID that the owner wants to act on * @dev allows an owner to act on a withdraw request */ function withdraw(uint _ballotID) public isOwner() isFrozen() { AccessAccount.freeze(); require(allBallots[_ballotID].amount < AccessAccount.balance, "Insufficent funds"); require(allBallots[_ballotID].typeOfVote == VoteType.withdrawRequest); require(votePassed(_ballotID)); allBallots[_ballotID].actedOn = true; AccessAccount.balance -= allBallots[_ballotID].amount; allBallots[_ballotID].currentAddress.transfer(allBallots[_ballotID].amount); AccessAccount.defrost(); } /** * @param _ballotID : the ballot ID that the owner wants to act on * @dev allows an owner to act on a change owner requst */ function changeOwnerAddress(uint _ballotID) public isOwner() isFrozen() { AccessAccount.freeze(); require(allOwners[ownersKeys[allBallots[_ballotID].currentAddress]].isOwner); require(allBallots[_ballotID].typeOfVote == VoteType.changeOwner); require(votePassed(_ballotID)); allOwners[ownersKeys[allBallots[_ballotID].currentAddress]].isOwner = false; noOfOwners++; ownersKeys[allBallots[_ballotID].newAddress] = noOfOwners; allOwners[ownersKeys[allBallots[_ballotID].newAddress]].isOwner = true; AccessAccount.defrost(); } /** * @param _ballotID : the ballot ID that the owner wants to act on * @dev allows an owner to act on an add request */ function addOwner(uint _ballotID) public isOwner() isFrozen() { AccessAccount.freeze(); require(allOwners[ownersKeys[allBallots[_ballotID].currentAddress]].isOwner); require(allBallots[_ballotID].typeOfVote == VoteType.addOwner); require(votePassed(_ballotID)); allBallots[_ballotID].actedOn = true; noOfOwners++; ownersKeys[allBallots[_ballotID].newAddress] = noOfOwners; allOwners[noOfOwners] = OwnerDetails({ isOwner: true, ownerWallet: allBallots[_ballotID].newAddress }); owners.push(allBallots[_ballotID].newAddress); AccessAccount.defrost(); } /** * @param _ballotID : the ballot ID that the owner wants to act on * @dev allows an owner to act on a remove request */ function removeOwner(uint _ballotID) public isOwner() isFrozen() { AccessAccount.freeze(); require(votePassed(_ballotID)); require(allBallots[_ballotID].typeOfVote == VoteType.removeOwner); allBallots[_ballotID].actedOn = true; allOwners[ownersKeys[allBallots[_ballotID].currentAddress]].isOwner = false; allOwners[ownersKeys[allBallots[_ballotID].currentAddress]].ownerWallet = 0x0; AccessAccount.defrost(); } /** * @dev Allows the bank to dissolve the account. * @notice the balance of the contract gets split between all the * currently active owners. */ function dissolve() public isBank() { frozen = true; uint valuePerOwnerCounter = 0; for(uint i = 0; i <= noOfOwners ; i++){ if(allOwners[i].isOwner) valuePerOwnerCounter++; } uint valuePerOwner = balance / valuePerOwnerCounter; for(uint a = 0; i <= noOfOwners ; a++){ if(allOwners[i].isOwner) allOwners[i].ownerWallet.transfer(valuePerOwner); } selfdestruct(bankAddress); } }
* @param _voteType : the type of vote it is @param _current : if it is removing / changing / adding an owner: if removing, this is the address of the owner to remove. if changing, _current is their current address. if adding an owner, current will be blank if withdraw requset, this is the address the funds will be sent to @param _new :if changing / adding an owner: if changing, this will be their new address if adding, contains the new address if withdraw request then this is blank @dev if the vote type is rejecting a withdraw requset then both addresses are empty/vote is owners modification3 (days) x 24 (hours) x 60 (minutes) x 60 (secounds) = 259 200vote is rejecting withdraw.
function createBallot(VoteType _voteType, address _current, address _new, uint _amount) private returns(uint newBallotID) { if( _voteType == VoteType.removeOwner || _voteType == VoteType.addOwner || _voteType == VoteType.changeOwner ){ allBallots[ballotIDs] = Ballot({ ballotID: ballotIDs, typeOfVote: _voteType, startTime: now, endTime: now + 259200, currentAddress: _current, newAddress: _new, amount: 0, actedOn: false, bankVoted: false, banksVote: false }); newBallotID = ballotIDs; ballotIDs++; allBallots[ballotIDs] = Ballot({ ballotID: ballotIDs, typeOfVote: _voteType, startTime: now, endTime: now + 259200, currentAddress: _current, newAddress: 0x0, amount: _amount, actedOn: false, bankVoted: false, banksVote: false }); newBallotID = ballotIDs; ballotIDs++; } return newBallotID; }
1,041,600
[ 1, 67, 25911, 559, 294, 326, 618, 434, 12501, 518, 353, 225, 389, 2972, 294, 309, 518, 353, 9427, 342, 12770, 342, 6534, 392, 3410, 30, 377, 309, 9427, 16, 333, 353, 326, 1758, 434, 326, 3410, 358, 1206, 18, 377, 309, 12770, 16, 389, 2972, 353, 3675, 783, 1758, 18, 377, 309, 6534, 392, 3410, 16, 783, 903, 506, 7052, 377, 309, 598, 9446, 10780, 542, 16, 333, 353, 326, 1758, 326, 284, 19156, 903, 506, 3271, 358, 225, 389, 2704, 294, 430, 12770, 342, 6534, 392, 3410, 30, 377, 309, 12770, 16, 333, 903, 506, 3675, 394, 1758, 377, 309, 6534, 16, 1914, 326, 394, 1758, 377, 309, 598, 9446, 590, 1508, 333, 353, 7052, 225, 309, 326, 12501, 618, 353, 4925, 310, 279, 598, 9446, 10780, 542, 1508, 3937, 6138, 854, 1008, 19, 25911, 353, 25937, 11544, 23, 261, 9810, 13, 619, 4248, 261, 16814, 13, 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, 752, 38, 454, 352, 12, 19338, 559, 389, 25911, 559, 16, 1758, 389, 2972, 16, 1758, 389, 2704, 16, 2254, 389, 8949, 13, 203, 3639, 3238, 203, 3639, 1135, 12, 11890, 394, 38, 454, 352, 734, 13, 203, 565, 288, 203, 3639, 309, 12, 203, 5411, 389, 25911, 559, 422, 27540, 559, 18, 4479, 5541, 747, 7010, 5411, 389, 25911, 559, 422, 27540, 559, 18, 1289, 5541, 747, 7010, 5411, 389, 25911, 559, 422, 27540, 559, 18, 3427, 5541, 203, 3639, 262, 95, 203, 5411, 777, 38, 454, 6968, 63, 19067, 352, 5103, 65, 273, 605, 454, 352, 12590, 203, 7734, 26503, 352, 734, 30, 26503, 352, 5103, 16, 203, 7734, 23170, 19338, 30, 389, 25911, 559, 16, 203, 7734, 8657, 30, 2037, 16, 203, 7734, 13859, 30, 2037, 397, 576, 6162, 6976, 16, 203, 7734, 783, 1887, 30, 389, 2972, 16, 203, 7734, 394, 1887, 30, 389, 2704, 16, 203, 7734, 3844, 30, 374, 16, 203, 7734, 1328, 329, 1398, 30, 629, 16, 203, 7734, 11218, 58, 16474, 30, 629, 16, 203, 7734, 11218, 87, 19338, 30, 629, 203, 5411, 15549, 203, 5411, 394, 38, 454, 352, 734, 273, 26503, 352, 5103, 31, 203, 5411, 26503, 352, 5103, 9904, 31, 203, 5411, 777, 38, 454, 6968, 63, 19067, 352, 5103, 65, 273, 605, 454, 352, 12590, 203, 7734, 26503, 352, 734, 30, 26503, 352, 5103, 16, 203, 7734, 23170, 19338, 30, 389, 25911, 559, 16, 203, 7734, 8657, 30, 2037, 16, 203, 7734, 13859, 30, 2037, 397, 576, 6162, 6976, 16, 2 ]
./full_match/1/0xc905E74BEb8229E258c3C6E5bC0D6Cc54C534688/sources/contracts/chainlink/ChainlinkOracleClient.sol
store the dstChainId and delivery address
function setDeliveryAddress(uint16 _dstChainId, address _deliveryAddress) public onlyOwner { deliveryAddressLookup[_dstChainId] = abi.encodePacked(_deliveryAddress); }
2,930,676
[ 1, 2233, 326, 3046, 3893, 548, 471, 7912, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 8909, 1887, 12, 11890, 2313, 389, 11057, 3893, 548, 16, 1758, 389, 15703, 1887, 13, 1071, 1338, 5541, 288, 203, 3639, 7912, 1887, 6609, 63, 67, 11057, 3893, 548, 65, 273, 24126, 18, 3015, 4420, 329, 24899, 15703, 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 ]
./full_match/1/0x0000007eE460B0928c2119E3B9747454A10d1557/sources/contracts/YunGouAggregators/YunGouAggregators.sol
get market details market should be active execute trade if is Proxy delegatecall, else call check if the call passed successfully
function _trade( MarketRegistry.TradeDetails[] calldata _tradeDetails ) internal { for (uint256 i = 0; i < _tradeDetails.length; i++) { (address _market, bool _isProxy, bool _isActive) = marketRegistry .markets(_tradeDetails[i].marketId); require(_isActive, "_trade: InActive Market"); (bool success, ) = _isProxy ? _market.delegatecall(_tradeDetails[i].tradeData) _tradeDetails[i].tradeData ); _checkCallResult(success); } }
17,111,552
[ 1, 588, 13667, 3189, 13667, 1410, 506, 2695, 1836, 18542, 309, 353, 7659, 7152, 1991, 16, 469, 745, 866, 309, 326, 745, 2275, 4985, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 20077, 12, 203, 3639, 6622, 278, 4243, 18, 22583, 3790, 8526, 745, 892, 389, 20077, 3790, 203, 565, 262, 2713, 288, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 20077, 3790, 18, 2469, 31, 277, 27245, 288, 203, 5411, 261, 2867, 389, 27151, 16, 1426, 389, 291, 3886, 16, 1426, 389, 291, 3896, 13, 273, 13667, 4243, 203, 7734, 263, 3355, 2413, 24899, 20077, 3790, 63, 77, 8009, 27151, 548, 1769, 203, 5411, 2583, 24899, 291, 3896, 16, 4192, 20077, 30, 657, 3896, 6622, 278, 8863, 203, 5411, 261, 6430, 2216, 16, 262, 273, 389, 291, 3886, 203, 7734, 692, 389, 27151, 18, 22216, 1991, 24899, 20077, 3790, 63, 77, 8009, 20077, 751, 13, 203, 10792, 389, 20077, 3790, 63, 77, 8009, 20077, 751, 203, 7734, 11272, 203, 5411, 389, 1893, 1477, 1253, 12, 4768, 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 ]
./full_match/5/0x66b1C6CC589d5bA470F348bbe81613269e1EC9A7/sources/solidity/contracts/DataFeedKeeper.sol
@inheritdoc IDataFeedKeeper TODO: review if the external call can be avoided
function work(bytes32 _poolSalt) external upkeep { if (!workable(_poolSalt)) revert NotWorkable(); (, uint32 _lastBlockTimestampObserved, , ) = dataFeed.lastPoolStateObserved(_poolSalt); uint32[] memory _secondsAgos = calculateSecondsAgos(periodLength, _lastBlockTimestampObserved); dataFeed.fetchObservations(_poolSalt, _secondsAgos); }
1,871,676
[ 1, 36, 10093, 467, 751, 8141, 17891, 2660, 30, 10725, 309, 326, 3903, 745, 848, 506, 1712, 11359, 785, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 1440, 12, 3890, 1578, 389, 6011, 19290, 13, 3903, 731, 10102, 288, 203, 565, 309, 16051, 1252, 429, 24899, 6011, 19290, 3719, 15226, 2288, 2421, 429, 5621, 203, 565, 261, 16, 2254, 1578, 389, 2722, 1768, 4921, 9013, 2155, 16, 269, 262, 273, 501, 8141, 18, 2722, 2864, 1119, 9013, 2155, 24899, 6011, 19290, 1769, 203, 565, 2254, 1578, 8526, 3778, 389, 7572, 2577, 538, 273, 4604, 6762, 2577, 538, 12, 6908, 1782, 16, 389, 2722, 1768, 4921, 9013, 2155, 1769, 203, 565, 501, 8141, 18, 5754, 26199, 1012, 24899, 6011, 19290, 16, 389, 7572, 2577, 538, 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 ]
// SPDX-License-Identifier: AGPL-3.0 // Feel free to change the license, but this is what we use // Feel free to change this version of Solidity. We support >=0.6.0 <0.7.0; pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // These are the core Yearn libraries import { BaseStrategy, StrategyParams } from "@yearnvaults/contracts/BaseStrategy.sol"; import "@openzeppelinV3/contracts/token/ERC20/IERC20.sol"; import "@openzeppelinV3/contracts/math/SafeMath.sol"; import "@openzeppelinV3/contracts/utils/Address.sol"; import "@openzeppelinV3/contracts/token/ERC20/SafeERC20.sol"; // Import interfaces for many popular DeFi projects, or add your own! //import "../interfaces/<protocol>/<Interface>.sol"; contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; constructor(address _vault) public BaseStrategy(_vault) { // You can set these parameters on deployment to whatever you want // minReportDelay = 6300; // profitFactor = 100; // debtThreshold = 0; } // ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************ function name() external override pure returns (string memory) { // Add your own name here, suggestion e.g. "StrategyCreamYFI" return "Strategy<ProtocolName><TokenType>"; } /* * 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 it's entire position based on * current on-chain conditions. * * NOTE: 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). * * NOTE: It is up to governance to use this function in order to correctly order * this strategy relative to its peers in order 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 it's expected value to be "safe". */ function estimatedTotalAssets() public override view returns (uint256) { // TODO: Build a more accurate estimate using the value of all positions in terms of `want` return want.balanceOf(address(this)); } /* * Perform any strategy unwinding or other calls necessary to capture the "free return" * this strategy has generated since the last time it's core position(s) were adjusted. * Examples include unwrapping extra rewards. This call is only used during "normal operation" * of a Strategy, and should be optimized to minimize losses as much as possible. This method * returns any realized profits and/or realized losses incurred, and should return the total * amounts of profits/losses/debt payments (in `want` tokens) for the Vault's accounting * (e.g. `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * 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. */ function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { // TODO: Do stuff here to free up any returns back into `want` // NOTE: Return `_profit` which is value generated by all positions, priced in `want` // NOTE: Should try to free up at least `_debtOutstanding` of underlying position } /* * 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. */ function adjustPosition(uint256 _debtOutstanding) internal override { // TODO: Do something to invest excess `want` tokens (from the Vault) into your positions // NOTE: Try to adjust positions so that `_debtOutstanding` can be freed up on *next* harvest (not immediately) } /* * Make as much capital as possible "free" for the Vault to take. Some * slippage is allowed. The goal is for the strategy to divest as quickly as possible * while not suffering exorbitant losses. This function is used during emergency exit * instead of `prepareReturn()`. This method returns any realized losses incurred, and * should also return the amount of `want` tokens available to repay outstanding debt * to the Vault. */ function exitPosition(uint256 _debtOutstanding) internal override returns (uint256 _profit, uint256 _loss, uint256 _debtPayment) { // TODO: Do stuff here to free up as much as possible of all positions back into `want` // TODO: returns any realized profit/losses incurred, and should also return the amount // of `want` tokens available to repay back to the Vault. } /* * Liquidate as many assets as possible to `want`, irregardless of slippage, * up to `_amountNeeded`. Any excess should be re-invested here as well. */ function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed) { // TODO: Do stuff here to free up to `_amountNeeded` from all positions back into `want` // NOTE: Return `_amountFreed`, which should be `<= _amountNeeded` } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary /* * Do anything necesseary to prepare this strategy for migration, such * as transfering any reserve or LP tokens, CDPs, or other tokens or stores of value. */ function prepareMigration(address _newStrategy) internal override { // TODO: Transfer any non-`want` tokens to the new strategy // NOTE: `migrate` will automatically forward all `want` in this strategy to the new one } // 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 override view returns (address[] memory) {} }
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./ TODO: Do something to invest excess `want` tokens (from the Vault) into your positions NOTE: Try to adjust positions so that `_debtOutstanding` can be freed up on *next* harvest (not immediately)
function adjustPosition(uint256 _debtOutstanding) internal override { }
1,754,289
[ 1, 4990, 1281, 5765, 1346, 358, 326, 2922, 1754, 12, 87, 13, 434, 333, 6252, 864, 4121, 2549, 326, 17329, 7165, 316, 326, 315, 5768, 395, 429, 12872, 6, 2319, 358, 326, 6252, 18, 3609, 716, 777, 315, 9156, 12872, 6, 316, 326, 6252, 1839, 326, 2605, 1703, 7165, 353, 2319, 364, 283, 5768, 395, 475, 18, 8080, 4721, 716, 333, 1300, 3377, 506, 374, 16, 471, 1846, 1410, 1640, 716, 10766, 15905, 18, 19, 2660, 30, 2256, 5943, 358, 2198, 395, 23183, 1375, 17369, 68, 2430, 261, 2080, 326, 17329, 13, 1368, 3433, 6865, 5219, 30, 6161, 358, 5765, 6865, 1427, 716, 1375, 67, 323, 23602, 1182, 15167, 68, 848, 506, 28004, 731, 603, 1024, 17895, 26923, 261, 902, 7636, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 5765, 2555, 12, 11890, 5034, 389, 323, 23602, 1182, 15167, 13, 2713, 3849, 288, 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, -100 ]
pragma solidity ^0.4.0; /// @title Abstract token contract - Functions to be implemented by token contracts. contract Token { function transfer(address to, uint256 value) public returns (bool success); function transferFrom(address from, address to, uint256 value) public returns (bool success); function approve(address spender, uint256 value) public returns (bool success); // This is not an abstract function, because solc won't recognize generated getter functions for public variables as functions. function totalSupply() public constant returns (uint256 supply); function balanceOf(address owner) public constant returns (uint256 balance); function allowance(address owner, address spender) public constant returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /// @title Standard token contract - Standard token interface implementation. contract StandardToken is Token { /* * Data structures */ mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public maxSupply; /* * Public functions */ /// @dev Transfers sender's tokens to a given address. Returns success. /// @param _to Address of token receiver. /// @param _value Number of tokens to transfer. /// @return Returns success of function call. function transfer(address _to, uint256 _value) public returns (bool) { if (balances[msg.sender] < _value) { // Balance too low revert(); } balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } /// @dev Allows allowed third party to transfer tokens from one address to another. Returns success. /// @param _from Address from where tokens are withdrawn. /// @param _to Address to where tokens are sent. /// @param _value Number of tokens to transfer. /// @return Returns success of function call. function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { if (balances[_from] < _value || allowed[_from][msg.sender] < _value) { // Balance or allowance too low revert(); } balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } /// @dev Sets approved amount of tokens for spender. Returns success. /// @param _spender Address of allowed account. /// @param _value Number of approved tokens. /// @return Returns success of function call. function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /* * Read functions */ /// @dev Returns number of allowed tokens for given address. /// @param _owner Address of token owner. /// @param _spender Address of token spender. /// @return Returns remaining allowance for spender. function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } /// @dev Returns number of tokens owned by given address. /// @param _owner Address of token owner. /// @return Returns balance of owner. function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } } // author: SuXeN contract SolarNA is StandardToken { /* * Token meta data */ string constant public name = "SolarNA Token"; string constant public symbol = "SOLA"; uint8 constant public decimals = 3; address public owner; uint remaining; uint divPrice = 10 ** 12; /* * Public functions */ /// @dev Contract constructor function gives tokens to presale_addresses and leave 100k tokens for sale. /// @param presale_addresses Array of addresses receiving preassigned tokens. /// @param tokens Array of preassigned token amounts. /// NB: Max 4 presale_addresses function SolarNA(address[] presale_addresses, uint[] tokens) public { uint assignedTokens; owner = msg.sender; maxSupply = 500000 * 10**3; for (uint i=0; i<presale_addresses.length; i++) { if (presale_addresses[i] == 0) { // Address should not be null. revert(); } balances[presale_addresses[i]] += tokens[i]; assignedTokens += tokens[i]; emit Transfer(0, presale_addresses[i], tokens[i]); // emit an event } /// If presale_addresses > 4 => The maxSupply will increase remaining = maxSupply - assignedTokens; assignedTokens += remaining; if (assignedTokens != maxSupply) { revert(); } } /// Change price from 1000 SOLA = 1 ether to 500 SOLA = 1 ether function changePrice(bool _conditon) public returns (uint) { require(msg.sender == owner); if (_conditon) { divPrice *= 2; } return divPrice; } function () public payable { /// Required msg.value > 0 and still remaining tokens uint value = msg.value / uint(divPrice); require(remaining >= value && value != 0); balances[msg.sender] += value; remaining -= value; emit Transfer(address(0), msg.sender, value); } /// Transfer all the funds in ETH to the owner function transferAll() public returns (bool) { require(msg.sender == owner); owner.transfer(address(this).balance); return true; } /// Return MaxSupply function totalSupply() public constant returns (uint256 supply) { return maxSupply; } /// Return remaining tokens function remainingTokens() public view returns (uint256) { return remaining; } }
Change price from 1000 SOLA = 1 ether to 500 SOLA = 1 ether
function changePrice(bool _conditon) public returns (uint) { require(msg.sender == owner); if (_conditon) { divPrice *= 2; } return divPrice; }
6,345,225
[ 1, 3043, 6205, 628, 4336, 27175, 37, 273, 404, 225, 2437, 358, 6604, 27175, 37, 273, 404, 225, 2437, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 2549, 5147, 12, 6430, 389, 10013, 26949, 13, 1071, 1135, 261, 11890, 13, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 3639, 309, 261, 67, 10013, 26949, 13, 288, 203, 5411, 3739, 5147, 6413, 576, 31, 203, 3639, 289, 203, 3639, 327, 3739, 5147, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <=0.9.0; // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol // 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 no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Counters.sol /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/IERC165.sol /** * @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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/ERC165.sol /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/IERC721.sol /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/extensions/IERC721Metadata.sol /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: contracts/BitPortraits.sol contract BitPortraits is ERC721, IERC721Receiver, Ownable { using SafeMath for uint256; using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIdx; uint256 public constant MAX_SUPPLY = 5102; uint256 public SALE_START_TIME = block.timestamp + (3600); // one hour after contract creation time uint256 public SALE_END_TIME = SALE_START_TIME + (30 * 86400); // 30 days or earlier address private contractOwner = 0x2c7dc51aD89359150Db406d18701AfD11D9F62d7; bool private saleIsLive = true; //BitPortraits Provenance is a (SHA256) hash of hashes of the following 5102 images, in the specified order: // 1) A 85x60 Collage of all 5100 BitPortraits ["BitPortraits Opus"] - DB65B2D5F32476E4E9E26BF598757D85EA5AD829BB3B9A97EA2818F376CB1B47 // 2) 5100 BitPortraits (600*800px) that are combinatorial variations of 05 distinct attributes of 300 Core-BitPortraits // 3) A 20x15 Collage of 300 Core-BitPortraits ["BitPortraits Core"] - 7854F278B632F8AD14FA5A136FC848792945DEDCA8F5E3704FAA23835A906C63 bytes32 public constant BP_PROVENANCE = 0xaafbe083b53cc7a741e377a27033190c093a246d9ef52f3374ae788535a228cf; // mapping for token hashes mapping (uint256 => bytes32) private _tokenHashes; event tokenHashSet (uint256 indexed tokenId_, bytes32 indexed tokenHash_); constructor() ERC721("BitPortraits", "BP") { //_safeMint(_msgSender(), 0); _safeMint(address(this), 0); _setTokenHash(0, 0xDB65B2D5F32476E4E9E26BF598757D85EA5AD829BB3B9A97EA2818F376CB1B47); _tokenIdx.increment(); transferOwnership(contractOwner); } function _baseURI() internal view virtual override returns (string memory) { return "bitportraits.com/token/"; } function totalSupply() public view returns (uint256) { return _tokenIdx.current(); } function saleLive() public view returns (bool) { return saleIsLive; } function transferOpus() onlyOwner public { if(ownerOf(0) == address(this)){ _safeTransfer(address(this), contractOwner, 0, ""); } } function _setTokenHash(uint256 tokenId_, bytes32 tokenHash_) onlyOwner public { require(_exists(tokenId_), "ERC721Metadata: Hash set of nonexistent token"); _tokenHashes[tokenId_] = tokenHash_; emit tokenHashSet(tokenId_, tokenHash_); } function tokenHash(uint256 tokenId_) public view returns (bytes32) { require(_exists(tokenId_), "ERC721Metadata: Hash query for nonexistent token"); //bytes32 _tokenHash = _tokenHashes[tokenId_]; //return _tokenHash; return _tokenHashes[tokenId_]; } function tierUpperBound(uint256 tierId_) private pure returns (uint256) { if (tierId_ == 1) { return 2401; } else if (tierId_ == 2) { return 3601; } else if (tierId_ == 3) { return 4201; } else if (tierId_ == 4) { return 4601; } else if (tierId_ == 5) { return 4901; } else if (tierId_ == 6) { return 5001; } else if (tierId_ == 7) { return 5101; } else { return 5102; } } function tierPrice(uint256 tierId_) private pure returns (uint256) { if (tierId_ == 1) { return 100000000000000000; // 0.1 ETH: 0001-2400 } else if (tierId_ == 2) { return 300000000000000000; // 0.3 ETH: 2401-3600 } else if (tierId_ == 3) { return 600000000000000000; // 0.6 ETH: 3601-4200 } else if (tierId_ == 4) { return 1000000000000000000; // 1.0 ETH: 4201-4600 } else if (tierId_ == 5) { return 2000000000000000000; // 2.0 ETH: 4601-4900 } else if (tierId_ == 6) { return 3000000000000000000; // 3.0 ETH: 4901-5000 } else if (tierId_ == 7) { return 6000000000000000000; // 6.0 ETH: 5001-5100 } else { return 510000000000000000000; // 510 ETH: 5101 } } function calcTokensSub(uint256 rxEther_, uint256 tierId_) private view returns (uint256) { require(totalSupply() <= tierUpperBound(tierId_), "Current Supply can't be greater than tierUpperBound"); uint256 tierUB; uint256 avlTierValue; uint256 avlTierSupply; uint256 overflowValue; uint256 numberOfTokens; tierUB = tierUpperBound(tierId_); avlTierSupply = tierUB.sub(totalSupply()); avlTierValue = avlTierSupply.mul(tierPrice(tierId_)); if (rxEther_ <= avlTierValue) { numberOfTokens = rxEther_.div(tierPrice(tierId_)); } else { overflowValue = rxEther_.sub(avlTierValue); numberOfTokens = avlTierSupply.add(overflowValue.div(tierPrice(tierId_.add(1)))); } return numberOfTokens; } function calcTokens(uint256 rxEther_) private view returns (uint256) { uint256 currentSupply; uint256 numberOfTokens; currentSupply = totalSupply(); if (currentSupply >= 1 && currentSupply <= 2381) { numberOfTokens = rxEther_.div(100000000000000000); // 0.1 ETH: 0001-2400 } else if (currentSupply >= 2381 && currentSupply < 2401) { numberOfTokens = calcTokensSub(rxEther_, 1); } else if (currentSupply >= 2401 && currentSupply < 3581) { numberOfTokens = rxEther_.div(300000000000000000); // 0.3 ETH: 2401-3600 } else if (currentSupply >= 3581 && currentSupply < 3601) { numberOfTokens = calcTokensSub(rxEther_, 2); } else if (currentSupply >= 3601 && currentSupply < 4181) { numberOfTokens = rxEther_.div(600000000000000000); // 0.6 ETH: 3601-4200 } else if (currentSupply >= 4181 && currentSupply < 4201) { numberOfTokens = calcTokensSub(rxEther_, 3); } else if (currentSupply >= 4201 && currentSupply < 4581) { numberOfTokens = rxEther_.div(1000000000000000000); // 1.0 ETH: 4201-4600 } else if (currentSupply >= 4581 && currentSupply < 4601) { numberOfTokens = calcTokensSub(rxEther_, 4); } else if (currentSupply >= 4601 && currentSupply < 4881) { numberOfTokens = rxEther_.div(2000000000000000000); // 2.0 ETH: 4601-4900 } else if (currentSupply >= 4881 && currentSupply < 4901) { numberOfTokens = calcTokensSub(rxEther_, 5); } else if (currentSupply >= 4901 && currentSupply < 4981) { numberOfTokens = rxEther_.div(3000000000000000000); // 3.0 ETH: 4901-5000 } else if (currentSupply >= 4981 && currentSupply < 5001) { numberOfTokens = calcTokensSub(rxEther_, 6); } else if (currentSupply >= 5001 && currentSupply < 5081) { numberOfTokens = rxEther_.div(6000000000000000000); // 6.0 ETH: 5001-5100 } else if (currentSupply >= 5081 && currentSupply < 5101) { numberOfTokens = calcTokensSub(rxEther_, 7); } else if (currentSupply == 5101) { numberOfTokens = rxEther_.div(510000000000000000000); // 510.0 ETH: 5102 if (numberOfTokens > 1) numberOfTokens = 1; //only one token here } else { numberOfTokens = 0; } // cap numberofTokens per transaction to 20 if (numberOfTokens > 20) numberOfTokens = 20; return numberOfTokens; } function mintTokens(address sender_, uint256 numberOfTokens_) private { require(totalSupply() <= MAX_SUPPLY, "Sale has already ended"); require(numberOfTokens_ > 0 && numberOfTokens_ <= 20, "tokens minted per transaction capped at 20"); for (uint256 i = 0; i < numberOfTokens_; i++) { _safeMint(sender_, totalSupply()); _tokenIdx.increment(); //_tokenIds.increment(); } if (totalSupply() == 5102 || block.timestamp > SALE_END_TIME) saleIsLive = false; } function mintRemaining(uint256 numberOfTokens_) onlyOwner public { mintTokens(_msgSender(), numberOfTokens_); } function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } function withdraw() onlyOwner public { payable(_msgSender()).transfer(address(this).balance); } receive() external payable { if(msg.value >= 5100000000000000000000) { //5100 ETH if (address(this) == ownerOf(0)){ _safeTransfer(address(this), _msgSender(), 0, ""); // transfer the opus (token zero) to the sender } } else if (saleIsLive && block.timestamp > SALE_START_TIME && block.timestamp < SALE_END_TIME) { require(totalSupply() <= MAX_SUPPLY, "Sale has already ended"); require(msg.value >= tierPrice(1), "Minimum required payment is 0.1 ETH"); mintTokens(_msgSender(), calcTokens(msg.value)); } } }
2.0 ETH: 4601-4900
numberOfTokens = rxEther_.div(2000000000000000000);
1,719,721
[ 1, 22, 18, 20, 512, 2455, 30, 17077, 1611, 17, 7616, 713, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 7922, 5157, 273, 8581, 41, 1136, 27799, 2892, 12, 22, 12648, 2787, 9449, 1769, 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 ]
./full_match/80001/0x990D76F1190D5098928cd2cAcCe0a2C9293EfBa8/sources/interfaces/v1/ISynsMarketplace.sol
@dev Emitted when the parameters of a listing are updated.
event ListingUpdated(uint256 indexed listingId, address indexed listingCreator);
845,956
[ 1, 1514, 11541, 1347, 326, 1472, 434, 279, 11591, 854, 3526, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 987, 310, 7381, 12, 11890, 5034, 8808, 11591, 548, 16, 1758, 8808, 11591, 10636, 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 ]
./full_match/5/0xDb80166478D50EDEFc4dD72c304d44D270c6b494/sources/contracts/core/AttestationsRegistry.sol
* @dev Getter of the data of specific attestations @param collectionIds Collection identifiers of the targeted attestations @param owners Owners of the targeted attestations/
function getAttestationDataBatch( uint256[] memory collectionIds, address[] memory owners ) external view override returns (AttestationData[] memory) { AttestationData[] memory attestationsDataArray = new AttestationData[](collectionIds.length); for (uint256 i = 0; i < collectionIds.length; i++) { attestationsDataArray[i] = _getAttestationData(collectionIds[i], owners[i]); } return attestationsDataArray; }
1,931,115
[ 1, 8461, 434, 326, 501, 434, 2923, 2403, 395, 1012, 225, 1849, 2673, 2200, 9863, 434, 326, 20715, 2403, 395, 1012, 225, 25937, 14223, 9646, 434, 326, 20715, 2403, 395, 1012, 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, 225, 445, 336, 3075, 395, 367, 751, 4497, 12, 203, 565, 2254, 5034, 8526, 3778, 1849, 2673, 16, 203, 565, 1758, 8526, 3778, 25937, 203, 225, 262, 3903, 1476, 3849, 1135, 261, 3075, 395, 367, 751, 8526, 3778, 13, 288, 203, 565, 6020, 395, 367, 751, 8526, 3778, 2403, 395, 1012, 751, 1076, 273, 394, 6020, 395, 367, 751, 8526, 12, 5548, 2673, 18, 2469, 1769, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1849, 2673, 18, 2469, 31, 277, 27245, 288, 203, 1377, 2403, 395, 1012, 751, 1076, 63, 77, 65, 273, 389, 588, 3075, 395, 367, 751, 12, 5548, 2673, 63, 77, 6487, 25937, 63, 77, 19226, 203, 565, 289, 203, 565, 327, 2403, 395, 1012, 751, 1076, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: SimPL-2.0 pragma solidity ^0.8.0; import "../client/node_modules/openzeppelin-solidity/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; contract ArmorAuction is ERC721Enumerable{ struct Magic_weapon{ string name; uint rarity;//0-100, 越大越稀有,在铸币时随机生成 } address payable public game_owner;//游戏拥有者账户 address public contract_address; Magic_weapon[] weapon_pool;//一方面可以记录自增ID,另一方面可以根据ID找稀有度 uint256[] onAuctions;//记录所有正在拍卖的物品的ID,从下标为1开始找 uint bidders_money;//合约上暂存的来自竞标者的钱 //初始化,合约拥有者为部署者 constructor() ERC721("LORDCOIN", "HCY") payable{ game_owner = payable(msg.sender); bidders_money = 0; contract_address = address(this); } //铸造NFT价格 uint soloPrice = 100000 wei; mapping (uint256 => uint256) private _is_selling;//物品id到当前价格的映射 mapping (uint256 => address payable) private _is_bidding;//物品到当前最高出价者的映射 mapping (uint256 => uint256) private onAuction_index;//物品id到它在onAuction数组中下标的映射 mapping (uint256 => uint256) private time_bound;//正在拍卖的物品id到截止时间戳的映射 mapping (bytes32 => bool) private name_unique; mapping (uint256 => address[]) private belongs_to;//归属权流转 event start_auction(address player, uint startprice, uint ID, uint timestart, uint timeend); event success_bid(address bidder, uint his_price, uint ID);//事件:为一件商品出了比当前价更高的价格 event auction_terminated(address winner, uint his_price, bool successed);//拍卖结束,取NFT的事件 //为某个客户铸造一个NFT,仅能由合约拥有者调用的函数 function forgeWeapon(address player, string memory weapon_name, uint _rarity) private returns (uint256) { uint256 newItemId = weapon_pool.length;//NFT的ID为自增,等于pool的长度 weapon_pool.push(Magic_weapon(weapon_name, _rarity)); _mint(player, newItemId);//分发NFT给客户 belongs_to[newItemId].push(player); return newItemId;//将ID返还给客户 } //客户调用该方法花钱向合约拥有者申请一项NFT,需要输入NFT的名字。 function applyWeapon(string memory weapon_name) public payable returns(uint256){ require(msg.value > soloPrice, "NFT price: more than 100000wei"); require(name_unique[keccak256(abi.encodePacked(weapon_name))] == false, "This name has beed token!"); //随机生成稀有度:0-100 name_unique[keccak256(abi.encodePacked(weapon_name))] = true; uint random = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender, msg.value))) % 100; uint256 ID = forgeWeapon(msg.sender, weapon_name, random); return ID; } //是否在售 function is_On_Auction(uint256 id) public view returns(bool){ if (_is_selling[id] != 0) return true; else return false; } //归属权流转信息 function showBelongings(uint256 id) public view returns(address[] memory owners){ return belongs_to[id]; } //获取客户自身拥有的所有NFT的数字ID function see_NFTS() public view returns(uint[] memory){ //获取拥有的NFT数 uint balance = balanceOf(msg.sender); uint256[] memory ret = new uint[](balance); for (uint i = 0; i < balance; i++) { ret[i] = uint256(tokenOfOwnerByIndex(msg.sender, i)); } return ret; } //获取客户自身拥有的单个NFT的name和稀有度 //参数: uint ID function see_NFT_info(uint ID) public view returns(string memory, uint){ string memory s = weapon_pool[ID].name; uint rare = weapon_pool[ID].rarity; return (s, rare); } //获取合约收到的铸币金额 function see_Profit() public view returns(uint){ return address(this).balance - bidders_money; } //合约将目前收到的钱转还给拥有者,赚麻了 function money_Feedback(uint _money) public{ require(msg.sender == game_owner && _money + bidders_money < address(this).balance, "Only game owner can get the profit"); game_owner.transfer(_money); return; } //限制器:只有商品拥有者才行 modifier onlyOwnerOf(uint weapon_Id) { require(msg.sender == ownerOf(weapon_Id), "Only owner of NFT can create an auction"); _; } //限制器:只有在给定time之后才行 modifier onlyAfter(uint256 _time) { require(block.timestamp > _time, "The auction is still going!"); _; } //限制器:只有在给定time之前才行 modifier onlyBefore(uint256 _time) { require(block.timestamp < _time, "The auction has already ended!"); _; } //开始一场拍卖 //参数:NFT的ID,初始价格,时间期限 function startAuction(uint256 weapon_Id, uint256 original_price, uint256 ddl) public onlyOwnerOf(weapon_Id) { require(isApprovedForAll(msg.sender, address(this)) == true, "Please grant approval of all your NFTs first."); require( _is_bidding[weapon_Id] == address(0) , "This item has been sold"); require(ddl > 1 minutes, "Time should >= 1 minutes"); _is_selling[weapon_Id] = original_price; _is_bidding[weapon_Id] = payable(msg.sender);//初始bidder设置为NFT拥有者 time_bound[weapon_Id] = block.timestamp + ddl;//设置期限 //将这个物品加入onAuction数组 onAuction_index[weapon_Id] = onAuctions.length; onAuctions.push(weapon_Id); } //查看所有正在拍卖物品信息,包括已经过期但是没有取下的拍卖 //返回值为所有正在拍卖的物品的ID, 一个数组 //onAuctions的第0下标被系统占用 function seeAllAuction() public view returns(uint[] memory){ uint i = 0; uint[] memory ret = new uint[](onAuctions.length); uint on; for (; i < onAuctions.length; i++) { on = onAuctions[i]; ret[i] = on; } return ret; } //查看某物品ID的拍卖相关信息 //参数:物品ID //返回值:当前价格,最高出价人,出售者,名称,稀有度,截止时间 function see_Auction_Info(uint256 ID) public view returns(uint, address, address, string memory, uint, uint){ require(ID < totalSupply() && _is_bidding[ID] != address(0), "The item is not being sold or doesn't exist"); uint price = _is_selling[ID]; address bidderNow = _is_bidding[ID]; address owner = ownerOf(ID); string memory name = weapon_pool[ID].name; uint r = weapon_pool[ID].rarity; uint ddl = time_bound[ID]; return (price, bidderNow, owner, name, r, ddl); } //为某物品竞标 //参数:物品ID, 消息附带的钱 //限制:在结束之前;不能自买自卖;不能出价低于当前价 function bidForWeapon(uint256 ID) public payable onlyBefore(time_bound[ID]){ require(isApprovedForAll(msg.sender, address(this)), "Please grant approval of all your NFTs first."); require(msg.value > _is_selling[ID], "Your price should higher than the current price"); require(msg.sender != ownerOf(ID), "Cannot bid your own items"); bidders_money += msg.value; //向上一个bidder退钱,需要判断是否有人出价 address payable lastbidder = _is_bidding[ID]; if (lastbidder != ownerOf(ID)){ payable(lastbidder).transfer(_is_selling[ID]); } //更新拍卖信息 _is_bidding[ID] = payable(msg.sender); _is_selling[ID] = msg.value; //触发竞标事件 emit success_bid(msg.sender, _is_selling[ID], ID); } //获取拍卖品:参数为NFT的ID //要求消息发送者是当前最高出价人, 且拍卖时间已过 //这个函数还会正式结束这场拍卖并将钱转给受益人 function claimAuction(uint256 weapon_Id) public { require(msg.sender == _is_bidding[weapon_Id], "You must be the bidder or owner to claim your NFT"); require(block.timestamp > time_bound[weapon_Id], "The auction has not ended"); //如果未售出, 则不发生转账和转移 if (msg.sender != ownerOf(weapon_Id)) { //合约转账最高竞标价格给原来的所有人, payable(ownerOf(weapon_Id)).transfer(_is_selling[weapon_Id]); //发生物品的转移 ArmorAuction(this).safeTransferFrom(ownerOf(weapon_Id), msg.sender, weapon_Id); //转钱 bidders_money -= _is_selling[weapon_Id]; //触发事件: 成功竞标并取走 belongs_to[weapon_Id].push(msg.sender); emit auction_terminated(msg.sender, _is_selling[weapon_Id], true); } else { //触发事件:没有人买,被原主人取走 emit auction_terminated(msg.sender, _is_selling[weapon_Id], false); } //在映射表中删除这件物品的拍卖信息 _is_selling[weapon_Id] = 0; _is_bidding[weapon_Id] = payable(address(0)); time_bound[weapon_Id] = 1 minutes; //从onAuction数组中删除这个物品: uint index = onAuction_index[weapon_Id]; uint lastindex = onAuctions.length - 1; if (index != lastindex) { //交换二者的位置信息 uint256 temp = onAuctions[index];//要删除的物品ID uint256 tempID = onAuctions[lastindex];//在数组最后一位的物品ID onAuctions[index] = onAuctions[lastindex]; onAuctions[lastindex] = temp; //更新被交换位置的物品ID的映射信息 onAuction_index[tempID] = index; } onAuctions.pop(); } }
获取客户自身拥有的所有NFT的数字ID获取拥有的NFT数
function see_NFTS() public view returns(uint[] memory){ uint balance = balanceOf(msg.sender); uint256[] memory ret = new uint[](balance); for (uint i = 0; i < balance; i++) { ret[i] = uint256(tokenOfOwnerByIndex(msg.sender, i)); } return ret; }
13,043,524
[ 1, 169, 241, 120, 166, 242, 249, 166, 111, 100, 167, 235, 120, 169, 234, 108, 169, 123, 109, 167, 238, 103, 167, 255, 236, 168, 253, 231, 167, 236, 227, 167, 255, 236, 50, 4464, 168, 253, 231, 167, 248, 113, 166, 260, 250, 734, 169, 241, 120, 166, 242, 249, 167, 238, 103, 167, 255, 236, 168, 253, 231, 50, 4464, 167, 248, 113, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2621, 67, 50, 4464, 55, 1435, 1071, 1476, 1135, 12, 11890, 8526, 3778, 15329, 203, 3639, 2254, 11013, 273, 11013, 951, 12, 3576, 18, 15330, 1769, 203, 3639, 2254, 5034, 8526, 3778, 325, 273, 394, 2254, 8526, 12, 12296, 1769, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 11013, 31, 277, 27245, 203, 3639, 288, 203, 5411, 325, 63, 77, 65, 273, 2254, 5034, 12, 2316, 951, 5541, 21268, 12, 3576, 18, 15330, 16, 277, 10019, 203, 3639, 289, 203, 3639, 327, 325, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x42AF47d643cb45D9a482AeD39c0973208f0CFAFF/sources/contracts/protocol/lib/Invoke.sol
* Instructs the JasperVault to wrap the passed quantity of ETH @param _jasperVault JasperVault instance to invoke @param _weth WETH address @param _quantity The quantity to unwrap/
function invokeWrapWETH(IJasperVault _jasperVault, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("deposit()"); _jasperVault.invoke(_weth, _quantity, callData); }
4,962,894
[ 1, 382, 1697, 87, 326, 804, 345, 457, 12003, 358, 2193, 326, 2275, 10457, 434, 512, 2455, 225, 389, 78, 345, 457, 12003, 3639, 804, 345, 457, 12003, 791, 358, 4356, 225, 389, 91, 546, 5411, 678, 1584, 44, 1758, 225, 389, 16172, 3639, 1021, 10457, 358, 11014, 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, 4356, 2964, 59, 1584, 44, 12, 45, 46, 345, 457, 12003, 389, 78, 345, 457, 12003, 16, 1758, 389, 91, 546, 16, 2254, 5034, 389, 16172, 13, 2713, 288, 203, 3639, 1731, 3778, 745, 751, 273, 24126, 18, 3015, 1190, 5374, 2932, 323, 1724, 1435, 8863, 203, 3639, 389, 78, 345, 457, 12003, 18, 14407, 24899, 91, 546, 16, 389, 16172, 16, 745, 751, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x4bCBcc5b5279d0dB55105Abd61b255b64680606D/sources/UniSwap_ETH_CDAIZap.sol
- fallback function let you / anyone send ETH to this wallet without the need to call any function
function() external payable { if (msg.sender != owner) { LetsInvest(address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE), msg.sender, 5);} }
2,763,261
[ 1, 17, 5922, 445, 2231, 1846, 342, 1281, 476, 1366, 512, 2455, 358, 333, 9230, 2887, 326, 1608, 358, 745, 1281, 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 ]
[ 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, 1435, 3903, 8843, 429, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 3410, 13, 288, 203, 5411, 511, 2413, 3605, 395, 12, 2867, 12, 20, 17432, 1340, 1340, 41, 1340, 73, 41, 73, 41, 1340, 41, 73, 41, 73, 41, 1340, 9383, 41, 1340, 1340, 41, 1340, 1340, 1340, 73, 9383, 73, 41, 3631, 1234, 18, 15330, 16, 1381, 1769, 97, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; import "./IDataEntity.sol"; /** * @title DataEntity Contract (parent for Kernel and Dataset contracts) * @author "Dr Maxim Orlovsky" <[email protected]> * * @dev Root contract for data entities and their workflows. For more details please refer to the * [Technical specification](https://github.com/pandoraboxchain/techspecs/wiki/Creating-data-entities) */ contract DataEntity is IDataEntity { /// @dev Address of IPFS metadata file in JSON format that contains all necessary information about data entity, /// together with references on other data files stored in IPFS (models, big data sets and data chunks etc) bytes public ipfsAddress; /// @dev Data dimension: sample data vector length for datasets and input layer vector length for AI kernel. /// Needs to be present in blockchain storage since used by the Pandora contract for checking during creation of /// cognitive job contract (dataset and kernel dimensions must match). uint256 public dataDim; /// @dev Current price (in PAN tokens) for the single use of the data entity uint256 public currentPrice; /// @dev Fired by `updatePrice` function event PriceUpdated(uint256 oldPrice, uint256 newPrice); constructor( bytes _ipfsAddress, uint256 _dataDim, uint256 _initialPrice ) public { dataDim = _dataDim; ipfsAddress = _ipfsAddress; currentPrice = _initialPrice; } function updatePrice ( uint256 _newPrice ) external onlyOwner { uint256 oldPrice = currentPrice; currentPrice = _newPrice; emit PriceUpdated(oldPrice, _newPrice); } /// @notice Withdraws full balance to the owner account. Can be called only by the owner of the contract. function withdrawBalance( // No arguments ) external onlyOwner // Can be called only by the owner { owner.transfer(address(this).balance); } }
@dev Address of IPFS metadata file in JSON format that contains all necessary information about data entity, together with references on other data files stored in IPFS (models, big data sets and data chunks etc) @dev Data dimension: sample data vector length for datasets and input layer vector length for AI kernel. Needs to be present in blockchain storage since used by the Pandora contract for checking during creation of cognitive job contract (dataset and kernel dimensions must match). @dev Current price (in PAN tokens) for the single use of the data entity @dev Fired by `updatePrice` function
public { dataDim = _dataDim; ipfsAddress = _ipfsAddress; currentPrice = _initialPrice; }
12,981,367
[ 1, 1887, 434, 2971, 4931, 1982, 585, 316, 1796, 740, 716, 1914, 777, 4573, 1779, 2973, 501, 1522, 16, 9475, 598, 5351, 603, 1308, 501, 1390, 4041, 316, 2971, 4931, 261, 7665, 16, 5446, 501, 1678, 471, 501, 6055, 5527, 13, 225, 1910, 4968, 30, 3296, 501, 3806, 769, 364, 11109, 471, 810, 3018, 3806, 769, 364, 432, 45, 5536, 18, 29164, 358, 506, 3430, 316, 16766, 2502, 3241, 1399, 635, 326, 453, 464, 10610, 6835, 364, 6728, 4982, 6710, 434, 276, 4198, 3720, 1719, 6835, 261, 8682, 471, 5536, 5769, 1297, 845, 2934, 225, 6562, 6205, 261, 267, 453, 1258, 2430, 13, 364, 326, 2202, 999, 434, 326, 501, 1522, 225, 478, 2921, 635, 1375, 2725, 5147, 68, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 1071, 288, 203, 3639, 501, 5225, 273, 389, 892, 5225, 31, 203, 3639, 2359, 2556, 1887, 273, 389, 625, 2556, 1887, 31, 203, 3639, 783, 5147, 273, 389, 6769, 5147, 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 ]
./partial_match/1/0x4B44e4305B42405382b7BeC717F64D0552a9D9Fe/sources/InboxValidatorManager.sol
* @notice Calculates and returns tree's current root/
function root() public view returns (bytes32) { return tree.root(); }
15,460,225
[ 1, 10587, 471, 1135, 2151, 1807, 783, 1365, 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, 1365, 1435, 1071, 1476, 1135, 261, 3890, 1578, 13, 288, 203, 3639, 327, 2151, 18, 3085, 5621, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.17; contract MillionairesProblem { // Stores # of millionaires that have joined and stated their net worths uint public numMillionaires; // Stores Millionaire structs (defined below) Millionaire[] millionaires; // Stores address of richest millionaire; set in callback function below address public richestMillionaire; address public owner; address public enigma; // Millionaire struct which holds encrypted address and net worth struct Millionaire { bytes myAddress; bytes myNetWorth; } // Event emitted upon callback completion; watched from front end event CallbackFinished(); // Modifier to ensure only enigma contract can call function modifier onlyEnigma() { require(msg.sender == enigma); _; } // Constructor called when new contract is deployed constructor(address _enigmaAddress, address _owner) public { owner = _owner; enigma = _enigmaAddress; } // Add a new millionaire with encrypted address and net worth arguments function addMillionaire(bytes _encryptedAddress, bytes _encryptedNetWorth) public { Millionaire memory millionaire = Millionaire({ myAddress: _encryptedAddress, myNetWorth: _encryptedNetWorth }); millionaires.push(millionaire); numMillionaires++; } // Return encrypted address and net worth for a particular millionaire function getInfoForMillionaire(uint index) public view returns (bytes, bytes) { Millionaire memory millionaire = millionaires[index]; bytes memory encryptedAddress = millionaire.myAddress; bytes memory encryptedNetWorth = millionaire.myNetWorth; return (encryptedAddress, encryptedNetWorth); } /* CALLABLE FUNCTION run in SGX to decipher encrypted net worths to determine richest millionaire */ function computeRichest(address[] _addresses, uint[] _netWorths) public pure returns (address) { uint maxIndex; uint maxValue; for (uint i = 0; i < _netWorths.length; i++) { if (_netWorths[i] >= maxValue) { maxValue = _netWorths[i]; maxIndex = i; } } return _addresses[maxIndex]; } /* CALLBACK FUNCTION to change contract state tracking richest millionaire's name */ function setRichestAddress(address _address) public onlyEnigma() { richestMillionaire = _address; emit CallbackFinished(); } }
Add a new millionaire with encrypted address and net worth arguments
function addMillionaire(bytes _encryptedAddress, bytes _encryptedNetWorth) public { Millionaire memory millionaire = Millionaire({ myAddress: _encryptedAddress, myNetWorth: _encryptedNetWorth }); millionaires.push(millionaire); numMillionaires++; }
14,021,437
[ 1, 986, 279, 394, 312, 737, 285, 69, 577, 598, 6901, 1758, 471, 2901, 26247, 1775, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 527, 49, 737, 285, 69, 577, 12, 3890, 389, 18702, 1887, 16, 1731, 389, 18702, 7308, 59, 7825, 13, 7010, 202, 202, 482, 7010, 202, 95, 203, 202, 202, 49, 737, 285, 69, 577, 3778, 312, 737, 285, 69, 577, 273, 490, 737, 285, 69, 577, 12590, 203, 1082, 202, 4811, 1887, 30, 389, 18702, 1887, 16, 7010, 1082, 202, 4811, 7308, 59, 7825, 30, 389, 18702, 7308, 59, 7825, 203, 202, 202, 22938, 7010, 202, 202, 81, 737, 285, 69, 2814, 18, 6206, 12, 81, 737, 285, 69, 577, 1769, 7010, 202, 202, 2107, 49, 737, 285, 69, 2814, 9904, 31, 7010, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2018 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.4.24; pragma experimental "v0.5.0"; /* solium-disable-next-line max-len*/ import { ForceRecoverCollateralDelegator } from "../margin/interfaces/lender/ForceRecoverCollateralDelegator.sol"; import { LoanOwner } from "../margin/interfaces/lender/LoanOwner.sol"; import { OnlyMargin } from "../margin/interfaces/OnlyMargin.sol"; contract TestForceRecoverCollateralDelegator is OnlyMargin, LoanOwner, ForceRecoverCollateralDelegator { address public RECOVERER; address public COLLATERAL_RECIPIENT; constructor( address margin, address recoverer, address recipient ) public OnlyMargin(margin) { RECOVERER = recoverer; COLLATERAL_RECIPIENT = recipient; } function receiveLoanOwnership( address, bytes32 ) onlyMargin external returns (address) { return address(this); } function forceRecoverCollateralOnBehalfOf( address recoverer, bytes32, address recipient ) onlyMargin external returns (address) { bool recovererOkay = (recoverer == RECOVERER); bool recipientOkay = (COLLATERAL_RECIPIENT != address(0)) && (recipient == COLLATERAL_RECIPIENT); require(recovererOkay || recipientOkay); return address(this); } }
solium-disable-next-line max-len*/
import { ForceRecoverCollateralDelegator } from "../margin/interfaces/lender/ForceRecoverCollateralDelegator.sol";
13,074,029
[ 1, 18281, 5077, 17, 8394, 17, 4285, 17, 1369, 943, 17, 1897, 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, 5666, 288, 11889, 27622, 13535, 2045, 287, 15608, 639, 289, 628, 315, 6216, 10107, 19, 15898, 19, 80, 2345, 19, 10997, 27622, 13535, 2045, 287, 15608, 639, 18, 18281, 14432, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; /** * @title Safe maths * @author https://theethereum.wiki/w/index.php/ERC20_Token_Standard */ library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "Bad maths."); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b <= a, "Bad maths."); c = a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a * b; require(a == 0 || c / a == b, "Bad maths."); } function div(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b > 0, "Bad maths."); c = a / b; } } /** * @title ERC Token Standard #20 Interface * @author https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md * @notice This is the basic interface for ERC20 that ensures all required functions exist. * @dev https://theethereum.wiki/w/index.php/ERC20_Token_Standard */ contract ERC20Interface { function totalSupply() public constant returns (uint256); function balanceOf(address tokenOwner) public constant returns (uint256 balance); function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining); function transfer(address to, uint256 tokens) public returns (bool success); function approve(address spender, uint256 tokens) public returns (bool success); function transferFrom(address from, address to, uint256 tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } /** * @title Contract function to receive approval and execute function in one call * @author https://theethereum.wiki/w/index.php/ERC20_Token_Standard * @dev Borrowed from MiniMeToken */ contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } /** * @title Owned Contract * @author https://theethereum.wiki/w/index.php/ERC20_Token_Standard * @notice Gives an inheriting contract the ability for certain functions to be * called only by the owner of the system. */ contract Owned { address internal owner; address internal newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } /** * @notice Modifier indicates that the function can only be called by owner */ modifier onlyOwner { require(msg.sender == owner, "Only the owner may execute this function."); _; } /** * @notice Give the ownership to the address _newOwner. Change only takes * place once the new owner accepts the ownership of this contract. * @param _newOwner The address of the new owner */ function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } /** * @notice Delete owner information */ function disown() public onlyOwner() { delete owner; } /** * @notice The new owner accepts responsibility of contract ownership * by using this function. */ function acceptOwnership() public { require(msg.sender == newOwner, "You have not been selected as the new owner."); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } /** * @title Snowden Token * @author David Edwards <Telecontrol Unterhaltungselektronik AG> * @notice This contract provides UltraUpload a token with which to * trade and receive dividends. * @dev Heavily derivative of the ERC20 Token Standard https://theethereum.wiki/w/index.php/ERC20_Token_Standard */ contract SnowdenToken is ERC20Interface, Owned { using SafeMath for uint256; string public symbol; string public name; uint8 public decimals; uint256 internal accountCount = 0; uint256 internal _totalSupply = 0; bool internal readOnly = false; uint256 internal constant MAX_256 = 2**256 - 1; mapping(address => bool) public ignoreDividend; event DividendGivenEvent(uint64 dividendPercentage); mapping(address => uint256) public freezeUntil; mapping(address => address) internal addressLinkedList; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; /** * @notice The token constructor. Creates the total supply. * @param supply The total number of coins to mint * @param addresses The addresses that will receive initial tokens * @param tokens The number of tokens that each address will receive * @param freezeList The unixepoch timestamp from which addresses are allowed to trade * @param ignoreList Addresses passed into this array will never receive dividends. The ignore list will always include this token contract. * * For example, if addresses is [ "0x1", "0x2" ], then tokens will need to have [ 1000, 8000 ] and freezeList will need to have [ 0, 0 ]. Numbers may change, but the values need to exist. */ constructor(uint256 supply, address[] addresses, uint256[] tokens, uint256[] freezeList, address[] ignoreList) public { symbol = "SNOW"; name = "Snowden"; decimals = 0; _totalSupply = supply; // * 10**uint(decimals); balances[address(0)] = _totalSupply; uint256 totalAddresses = addresses.length; uint256 totalTokens = tokens.length; // Must have positive number of addresses and tokens require(totalAddresses > 0 && totalTokens > 0, "Must be a positive number of addresses and tokens."); // Require same number of addresses as tokens require(totalAddresses == totalTokens, "Must be tokens assigned to all addresses."); uint256 aggregateTokens = 0; for (uint256 i = 0; i < totalAddresses; i++) { // Do not allow empty tokens – although this would have no impact on // the mappings (a 0 count on the mapping will not result in a new entry). // It is better to break here to ensure that there was no input error. require(tokens[i] > 0, "No empty tokens allowed."); aggregateTokens = aggregateTokens + tokens[i]; // Supply should always be more than the number of tokens given out! require(aggregateTokens <= supply, "Supply is not enough for demand."); giveReserveTo(addresses[i], tokens[i]); freezeUntil[addresses[i]] = freezeList[i]; } ignoreDividend[address(this)] = true; ignoreDividend[msg.sender] = true; for (i = 0; i < ignoreList.length; i++) { ignoreDividend[ignoreList[i]] = true; } } /** * @notice Fallback function reverts all paid ether. Do not accept payments. */ function () public payable { revert(); } /** * @notice Total supply, including in reserve * @return The number of tokens in circulation */ function totalSupply() public constant returns (uint256) { return _totalSupply; // (we use the local address to store the rest) - balances[address(0)]; } /** * @notice Return a list of addresses and their tokens * @return Two arrays, the first a list of addresses, the second a list of * token amounts. Each index matches the other. */ function list() public view returns (address[], uint256[]) { address[] memory addrs = new address[](accountCount); uint256[] memory tokens = new uint256[](accountCount); uint256 i = 0; address current = addressLinkedList[0]; while (current != 0) { addrs[i] = current; tokens[i] = balances[current]; current = addressLinkedList[current]; i++; } return (addrs, tokens); } /** * @notice Return the number of tokens not provisioned * @return The total number of tokens left in the reserve pool */ function remainingTokens() public view returns(uint256) { return balances[address(0)]; } /** * @return Is the contract set to readonly */ function isReadOnly() public view returns(bool) { return readOnly; } /** * @notice Get the token balance for account `tokenOwner` * @param tokenOwner Address of the account to get the number of tokens for * @return The number of tokens the address has */ function balanceOf(address tokenOwner) public constant returns (uint256 balance) { return balances[tokenOwner]; } /** * @notice Ensure that account is allowed to trade * @param from Address of the account to send from * @return True if this trade is allowed */ function requireTrade(address from) public view { require(!readOnly, "Read only mode engaged"); uint256 i = 0; address current = addressLinkedList[0]; while (current != 0) { if(current == from) { uint256 timestamp = freezeUntil[current]; require(timestamp < block.timestamp, "Trades from your account are temporarily not possible. This is due to ICO rules."); break; } current = addressLinkedList[current]; i++; } } /** * @notice Transfer the balance from token owner's account to `to` account * - Owner's account must have sufficient balance to transfer * - 0 value transfers are allowed * @param to Address to transfer tokens to * @param tokens Number of tokens to be transferred */ function transfer(address to, uint256 tokens) public returns (bool success) { requireTrade(msg.sender); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); ensureInAccountList(to); return true; } /** * @notice Token owner can approve for `spender` to transferFrom(...) `tokens` * from the token owner's account * @param spender address of the spender to approve * @param tokens Number of tokens to allow spender to spend * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md * recommends that there are no checks for the approval double-spend attack * as this should be implemented in user interfaces */ function approve(address spender, uint256 tokens) public returns (bool success) { requireTrade(msg.sender); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } /** * @notice Transfer `tokens` from the `from` account to the `to` account * @param from address to transfer tokens from * @param to address to transfer tokens to * @param tokens Number of tokens to transfer * @dev The calling account must already have sufficient tokens approve(...)-d * for spending from the `from` account and * - From account must have sufficient balance to transfer * - Spender must have sufficient allowance to transfer * - 0 value transfers are allowed */ function transferFrom(address from, address to, uint256 tokens) public returns (bool success) { requireTrade(from); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); ensureInAccountList(from); ensureInAccountList(to); return true; } /** * @notice Returns the amount of tokens approved by the owner that can be * transferred to the spender's account * @param tokenOwner The address of the owner of the token * @param spender The address of the spender of the token * @return Number of tokens that are approved for spending from the tokenOwner */ function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining) { requireTrade(tokenOwner); return allowed[tokenOwner][spender]; } /** * @notice Token owner can approve for `spender` to transferFrom(...) `tokens` * from the token owner's account. The `spender` contract function * `receiveApproval(...)` is then executed * @param spender address with which to approve * @param tokens The number of tokens that this address is approved to take * @param data Pass data to receiveApproval */ function approveAndCall(address spender, uint256 tokens, bytes data) public returns (bool success) { requireTrade(msg.sender); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } /** * @notice In the event of errors, allow the owner to move tokens from an account * @param addr address to take tokens from * @param tokens The number of tokens to take */ function transferAnyERC20Token(address addr, uint256 tokens) public onlyOwner returns (bool success) { requireTrade(addr); return ERC20Interface(addr).transfer(owner, tokens); } /** * @notice Give tokens from the pool to account, creating the account if necessary * @param to The address to deliver the new tokens to * @param tokens The number of tokens to deliver */ function giveReserveTo(address to, uint256 tokens) public onlyOwner { require(!readOnly, "Read only mode engaged"); balances[address(0)] = balances[address(0)].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(address(0), to, tokens); ensureInAccountList(to); } /** * @notice Distribute dividends to all owners * @param percentage Given in the form 1% === 10000. This is not a number of * tokens, more a form of percentage that does not require decimals. This * supports 0.00001% (with 1 as the percentage value). * @dev Dividends are rounded down, if a user has too few tokens, they will not receive anything */ function giveDividend(uint64 percentage) public onlyOwner { require(!readOnly, "Read only mode engaged"); require(percentage > 0, "Percentage must be more than 0 (10000 = 1%)"); // At least 0.00001% dividends require(percentage <= 500000, "Percentage may not be larger than 500000 (50%)"); // No more than 50% dividends emit DividendGivenEvent(percentage); address current = addressLinkedList[0]; while (current != 0) { bool found = ignoreDividend[current]; if(!found) { uint256 extraTokens = (balances[current] * percentage) / 1000000; giveReserveTo(current, extraTokens); } current = addressLinkedList[current]; } } /** * @notice Allow admins to (en|dis)able all write functionality for emergencies * @param enabled true to enable read only mode, false to allow writing */ function setReadOnly(bool enabled) public onlyOwner { readOnly = enabled; } /** * @notice Add an account to a linked list * @param addr address of the account to add to the linked list * @dev This is necessary to iterate over for listing purposes */ function addToAccountList(address addr) internal { require(!readOnly, "Read only mode engaged"); addressLinkedList[addr] = addressLinkedList[0x0]; addressLinkedList[0x0] = addr; accountCount++; } /** * @notice Remove an account from a linked list * @param addr address of the account to remove from the linked list * @dev This is necessary to iterate over for listing purposes */ function removeFromAccountList(address addr) internal { require(!readOnly, "Read only mode engaged"); uint16 i = 0; bool found = false; address parent; address current = addressLinkedList[0]; while (true) { if (addressLinkedList[current] == addr) { parent = current; found = true; break; } current = addressLinkedList[current]; if (i++ > accountCount) break; } require(found, "Account was not found to remove."); addressLinkedList[parent] = addressLinkedList[addressLinkedList[parent]]; delete addressLinkedList[addr]; if (balances[addr] > 0) { balances[address(0)] += balances[addr]; } delete balances[addr]; accountCount--; } /** * @notice Make sure that this address exists in our linked list * @param addr address of the account to test * @dev This is necessary to iterate over for listing purposes */ function ensureInAccountList(address addr) internal { require(!readOnly, "Read only mode engaged"); bool found = false; address current = addressLinkedList[0]; while (current != 0) { if (current == addr) { found = true; break; } current = addressLinkedList[current]; } if (!found) { addToAccountList(addr); } } }
* @notice In the event of errors, allow the owner to move tokens from an account @param addr address to take tokens from @param tokens The number of tokens to take/
function transferAnyERC20Token(address addr, uint256 tokens) public onlyOwner returns (bool success) { requireTrade(addr); return ERC20Interface(addr).transfer(owner, tokens); }
12,664,370
[ 1, 382, 326, 871, 434, 1334, 16, 1699, 326, 3410, 358, 3635, 2430, 628, 392, 2236, 225, 3091, 1758, 358, 4862, 2430, 628, 225, 2430, 1021, 1300, 434, 2430, 358, 4862, 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, 7412, 2961, 654, 39, 3462, 1345, 12, 2867, 3091, 16, 2254, 5034, 2430, 13, 1071, 1338, 5541, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2583, 22583, 12, 4793, 1769, 203, 3639, 327, 4232, 39, 3462, 1358, 12, 4793, 2934, 13866, 12, 8443, 16, 2430, 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 ]
//SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; // Interface for our erc20 token interface IToken { function totalSupply() external view returns (uint256); function balanceOf(address tokenOwner) external view returns (uint256 balance); function allowance(address tokenOwner, address spender) external view returns (uint256 remaining); function transfer(address to, uint256 tokens) external returns (bool success); function approve(address spender, uint256 tokens) external returns (bool success); function transferFrom( address from, address to, uint256 tokens ) external returns (bool success); function mint(address to, uint256 amount) external; function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; } contract CudlFinanceV5 is Initializable, ERC721HolderUpgradeable, OwnableUpgradeable { address public mooncats; address public PONDERWARE; address public MUSE_DAO; address public MUSE_DEVS; uint256 public gas; // if gas higher then this you can't kill uint256 public lastGas; //here we record last gas paid, to keep track of chain gas. If gas is high, no pets can die. IToken public token; struct Pet { address nft; uint256 id; } mapping(address => bool) public supportedNfts; mapping(uint256 => Pet) public petDetails; // mining tokens mapping(uint256 => uint256) public lastTimeMined; // Pet properties mapping(uint256 => uint256) public timeUntilStarving; mapping(uint256 => uint256) public petScore; mapping(uint256 => bool) public petDead; mapping(uint256 => uint256) public timePetBorn; // items/benefits for the PET could be anything in the future. mapping(uint256 => uint256) public itemPrice; mapping(uint256 => uint256) public itemPoints; mapping(uint256 => string) public itemName; mapping(uint256 => uint256) public itemTimeExtension; mapping(uint256 => mapping(address => address)) public careTaker; mapping(address => mapping(uint256 => bool)) public isNftInTheGame; //keeps track if nft already played mapping(address => mapping(uint256 => uint256)) public nftToId; //keeps track if nft already played uint256 public feesEarned; using CountersUpgradeable for CountersUpgradeable.Counter; CountersUpgradeable.Counter private _tokenIds; CountersUpgradeable.Counter private _itemIds; event Mined(uint256 nftId, uint256 reward, address recipient); event BuyAccessory( uint256 nftId, uint256 itemId, uint256 amount, uint256 itemTimeExtension, address buyer ); event Fatalize(uint256 opponentId, uint256 nftId, address killer); event NewPlayer( address nftAddress, uint256 nftId, uint256 playerId, address owner ); event Bonk( uint256 attacker, uint256 victim, uint256 winner, uint256 reward ); // Rewards algorithm uint256 public la; uint256 public lb; uint256 public ra; uint256 public rb; address public lastBonker; // NEW STORE v2 mapping(uint256 => uint256) public spent; mapping(address => uint256) public balance; mapping(address => bool) public isOperator; constructor() {} modifier isAllowed(uint256 _id) { Pet memory _pet = petDetails[_id]; address ownerOf = IERC721Upgradeable(_pet.nft).ownerOf(_pet.id); require( ownerOf == msg.sender || careTaker[_id][ownerOf] == msg.sender, "!owner" ); _; } modifier onlyOperator() { require( isOperator[msg.sender], "Roles: caller does not have the OPERATOR role" ); _; } // GAME ACTIONS function depositCudl(uint256 amount) external { balance[msg.sender] += amount; // burn real cul token.burnFrom(msg.sender, amount); } //this withdraws all your eanrings function claimRewards(uint256[] memory petIds) public { lastGas = tx.gasprice; uint256 amount; for (uint256 i = 0; i < petIds.length; i++) { require(isPetOwner(petIds[i], msg.sender), "!owner"); // This enforces helping kills/broadcast txs as you won't mine with any pet unless you kill your deads require( isPetSafe(petIds[i]), "Your pet is starving, you can't mine" ); uint256 earning = getEarnings(petIds[i]); if (earning > 0) { if (lastTimeMined[petIds[i]] == 0) { lastTimeMined[petIds[i]] = block.timestamp; } amount += earning; lastTimeMined[petIds[i]] = block.timestamp; emit Mined(petIds[i], earning, msg.sender); } } amount += balance[msg.sender]; balance[msg.sender] = 0; if (amount > 0) token.mint(msg.sender, amount); } function buyAccesory(uint256 nftId, uint256 itemId) public isAllowed(nftId) { require(!petDead[nftId], "ded pet"); uint256 amount = itemPrice[itemId]; require(amount > 0, "item does not exist"); // recalculate time until starving timeUntilStarving[nftId] = block.timestamp + itemTimeExtension[itemId]; petScore[nftId] += itemPoints[itemId]; if (getEarnings(nftId) >= amount) { spent[nftId] += amount; } else if (balance[msg.sender] >= amount) { balance[msg.sender] -= amount; } else { revert("bal"); } feesEarned += amount / 10; emit BuyAccessory( nftId, itemId, amount, itemTimeExtension[itemId], msg.sender ); } function feedMultiple(uint256[] calldata ids, uint256[] calldata itemIds) external { for (uint256 i = 0; i < ids.length; i++) { buyAccesory(ids[i], itemIds[i]); } } //TOOD DECIDE FATALITY function fatality(uint256 _deadId, uint256 _tokenId) external { require( !isPetSafe(_deadId) && tx.gasprice <= gas && //inspired by NFT GAS by 0Xmons petDead[_deadId] == false, "The PET has to be starved or gas below ${gas} to claim his points" ); petScore[_tokenId] = petScore[_tokenId] + (((petScore[_deadId] * (20)) / (100))); petScore[_deadId] = 0; petDead[_deadId] = true; emit Fatalize(_deadId, _tokenId, msg.sender); } function getCareTaker(uint256 _tokenId, address _owner) public view returns (address) { return (careTaker[_tokenId][_owner]); } function setCareTaker( uint256 _tokenId, address _careTaker, bool clearCareTaker ) external isAllowed(_tokenId) { if (clearCareTaker) { delete careTaker[_tokenId][msg.sender]; } else { careTaker[_tokenId][msg.sender] = _careTaker; } } // requires approval function giveLife(address nft, uint256 _id) external { require(IERC721Upgradeable(nft).ownerOf(_id) == msg.sender, "!OWNER"); require( !isNftInTheGame[nft][_id], "this nft was already registered can't again" ); require(supportedNfts[nft], "!forbidden"); // burn 6 cudl to join token.burnFrom(msg.sender, 100 * 1 ether); uint256 newId = _tokenIds.current(); // set the pet struct petDetails[newId] = Pet(nft, _id); nftToId[nft][_id] = newId; isNftInTheGame[nft][_id] = true; timeUntilStarving[newId] = block.timestamp + 3 days; //start with 3 days of life. timePetBorn[newId] = block.timestamp; emit NewPlayer(nft, _id, newId, msg.sender); _tokenIds.increment(); } // BAZAAR function burnScore(uint256 petId, uint256 amount) external onlyOperator { require(!petDead[petId]); petScore[petId] -= amount; } function addScore(uint256 petId, uint256 amount) external onlyOperator { require(!petDead[petId]); petScore[petId] += amount; } function spend(uint256 petId, uint256 amount) external onlyOperator { spent[petId] -= amount; } function gibCudl(uint256 petId, uint256 amount) external onlyOperator { spent[petId] += amount; } function addTOD(uint256 petId, uint256 duration) external onlyOperator { require(!petDead[petId]); timeUntilStarving[petId] = block.timestamp + duration; } function isPetOwner(uint256 petId, address user) public view returns (bool) { Pet memory _pet = petDetails[petId]; address ownerOf = IERC721Upgradeable(_pet.nft).ownerOf(_pet.id); return (ownerOf == user || careTaker[petId][ownerOf] == user); } // GETTERS function getEarnings(uint256 petId) public view returns (uint256) { uint256 amount = (((block.timestamp - lastTimeMined[petId]) / 1 days) * getRewards(petId)); if (amount <= spent[petId]) { return 0; } else { return amount - spent[petId]; } } function getPendingBalance(uint256[] memory petIds, address user) public view returns (uint256) { uint256 total; for (uint256 i = 0; i < petIds.length; i++) { total += getEarnings(petIds[i]); } return total + balance[user]; } // check that pet didn't starve function isPetSafe(uint256 _nftId) public view returns (bool) { uint256 _timeUntilStarving = timeUntilStarving[_nftId]; if ( (_timeUntilStarving != 0 && _timeUntilStarving >= block.timestamp) || lastGas >= gas ) { return true; } else { return false; } } // GETTERS function getPetInfo(uint256 _nftId) public view returns ( uint256 _pet, bool _isStarving, uint256 _score, uint256 _level, uint256 _expectedReward, uint256 _timeUntilStarving, uint256 _lastTimeMined, uint256 _timepetBorn, address _owner, address _token, uint256 _tokenId, bool _isAlive ) { Pet memory thisPet = petDetails[_nftId]; _pet = _nftId; _isStarving = !this.isPetSafe(_nftId); _score = petScore[_nftId]; _level = level(_nftId); _expectedReward = getRewards(_nftId); _timeUntilStarving = timeUntilStarving[_nftId]; _lastTimeMined = lastTimeMined[_nftId]; _timepetBorn = timePetBorn[_nftId]; _owner = IERC721Upgradeable(thisPet.nft).ownerOf(thisPet.id); _token = petDetails[_nftId].nft; _tokenId = petDetails[_nftId].id; _isAlive = !petDead[_nftId]; } // get the level the pet is on to calculate the token reward function getRewards(uint256 tokenId) public view returns (uint256) { // This is the formula to get token rewards R(level)=(level)*6/7+6 uint256 _level = level(tokenId); if (_level == 1) { return 6 ether; } _level = (_level * 1 ether * ra) / rb; return (_level + 5 ether); } // get the level the pet is on to calculate points function level(uint256 tokenId) public view returns (uint256) { // This is the formula L(x) = 2 * sqrt(x * 2) uint256 _score = petScore[tokenId] / 100; if (_score == 0) { return 1; } uint256 _level = sqrtu(_score * la); return (_level * lb); } // ADMIN function editCurves( uint256 _la, uint256 _lb, uint256 _ra, uint256 _rb ) external onlyOwner { la = _la; lb = _lb; ra = _ra; rb = _rb; } // edit specific item in case token goes up in value and the price for items gets to expensive for normal users. function editItem( uint256 _id, uint256 _price, uint256 _points, string calldata _name, uint256 _timeExtension ) external onlyOwner { itemPrice[_id] = _price; itemPoints[_id] = _points; itemName[_id] = _name; itemTimeExtension[_id] = _timeExtension; } // to support more projects function setSupported(address _nft, bool isSupported) public onlyOwner { supportedNfts[_nft] = isSupported; } function setGas(uint256 _gas) public onlyOwner { gas = _gas; } function addOperator(address _address, bool _isAllowed) public onlyOwner { isOperator[_address] = _isAllowed; } // add items/accessories function createItem( string calldata name, uint256 price, uint256 points, uint256 timeExtension ) external onlyOwner { _itemIds.increment(); uint256 newItemId = _itemIds.current(); itemName[newItemId] = name; itemPrice[newItemId] = price; itemPoints[newItemId] = points; itemTimeExtension[newItemId] = timeExtension; } function changeEarners(address _newAddress) public { require( msg.sender == MUSE_DEVS || msg.sender == PONDERWARE, "!forbidden" ); if (msg.sender == MUSE_DEVS) { MUSE_DEVS = _newAddress; } else if (msg.sender == PONDERWARE) { PONDERWARE = _newAddress; } } // anyone can call this function claimEarnings() public { token.mint(address(this), feesEarned); feesEarned = 0; uint256 bal = token.balanceOf(address(this)); token.transfer(PONDERWARE, bal / 3); token.transfer(MUSE_DAO, bal / 3); token.transfer(MUSE_DEVS, bal / 3); } function randomNumber(uint256 seed, uint256 max) public view returns (uint256 _randomNumber) { uint256 n = 0; unchecked { for (uint256 i = 0; i < 5; i++) { n += uint256( keccak256( abi.encodePacked(blockhash(block.number - i - 1), seed) ) ); } } return (n) % max; } function sqrtu(uint256 x) private pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128(r < r1 ? r : r1); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT 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 pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721ReceiverUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @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 ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable { function __ERC721Holder_init() internal initializer { __ERC721Holder_init_unchained(); } function __ERC721Holder_init_unchained() internal initializer { } /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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); }
recalculate time until starving
function buyAccesory(uint256 nftId, uint256 itemId) public isAllowed(nftId) { require(!petDead[nftId], "ded pet"); uint256 amount = itemPrice[itemId]; require(amount > 0, "item does not exist"); timeUntilStarving[nftId] = block.timestamp + itemTimeExtension[itemId]; petScore[nftId] += itemPoints[itemId]; if (getEarnings(nftId) >= amount) { spent[nftId] += amount; balance[msg.sender] -= amount; revert("bal"); } feesEarned += amount / 10; emit BuyAccessory( nftId, itemId, amount, itemTimeExtension[itemId], msg.sender ); }
10,325,943
[ 1, 266, 11162, 813, 3180, 10443, 6282, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 30143, 9988, 764, 630, 12, 11890, 5034, 290, 1222, 548, 16, 2254, 5034, 18424, 13, 203, 3639, 1071, 203, 3639, 21956, 12, 82, 1222, 548, 13, 203, 565, 288, 203, 3639, 2583, 12, 5, 6951, 11852, 63, 82, 1222, 548, 6487, 315, 785, 293, 278, 8863, 203, 203, 3639, 2254, 5034, 3844, 273, 761, 5147, 63, 1726, 548, 15533, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 1726, 1552, 486, 1005, 8863, 203, 203, 3639, 813, 9716, 18379, 6282, 63, 82, 1222, 548, 65, 273, 1203, 18, 5508, 397, 761, 950, 3625, 63, 1726, 548, 15533, 203, 3639, 293, 278, 7295, 63, 82, 1222, 548, 65, 1011, 761, 5636, 63, 1726, 548, 15533, 203, 203, 3639, 309, 261, 588, 41, 1303, 899, 12, 82, 1222, 548, 13, 1545, 3844, 13, 288, 203, 5411, 26515, 63, 82, 1222, 548, 65, 1011, 3844, 31, 203, 5411, 11013, 63, 3576, 18, 15330, 65, 3947, 3844, 31, 203, 5411, 15226, 2932, 70, 287, 8863, 203, 3639, 289, 203, 203, 3639, 1656, 281, 41, 1303, 329, 1011, 3844, 342, 1728, 31, 203, 203, 3639, 3626, 605, 9835, 1862, 630, 12, 203, 5411, 290, 1222, 548, 16, 203, 5411, 18424, 16, 203, 5411, 3844, 16, 203, 5411, 761, 950, 3625, 63, 1726, 548, 6487, 203, 5411, 1234, 18, 15330, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x18464e4584759A50CE9FC58eA5997F8B0D1EA1d8/sources/XIVDatabase.sol
array of user's address who has staked..
address[] userStakedAddress;
3,119,665
[ 1, 1126, 434, 729, 1807, 1758, 10354, 711, 384, 9477, 838, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 8526, 729, 510, 9477, 1887, 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 ]
./full_match/1/0xf6fc9f12092DE4579370F17516f09e2235e43b89/sources/contracts/importManager/main.sol
@notice import mark. avoSafe -> sender -> protocolId -> imported status (0 -> not imported, 1 -> in process, 2 -> imported)
mapping(address => mapping(address => mapping(uint256 => uint8))) public imports;
4,849,006
[ 1, 5666, 2267, 18, 1712, 83, 9890, 317, 5793, 317, 1771, 548, 317, 9101, 1267, 261, 20, 317, 486, 9101, 16, 404, 317, 316, 1207, 16, 576, 317, 9101, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2874, 12, 11890, 5034, 516, 2254, 28, 20349, 1071, 10095, 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 ]
// SPDX-License-Identifier: GPL-3.0 /// @title Wizards ERC-721 token pragma solidity ^0.8.6; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {IDescriptor} from "./descriptor/IDescriptor.sol"; import {ISeeder} from "./seeder/ISeeder.sol"; import {ERC721} from "../base/ERC721.sol"; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import {IProxyRegistry} from "../external/opensea/IProxyRegistry.sol"; import {IWizardToken} from "./IWizards.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "../external/rarible/RoyaltiesV2Impl.sol"; import "../external/rarible/LibPart.sol"; import "../external/rarible/LibRoyaltiesV2.sol"; contract WizardToken is IWizardToken, ERC721, Ownable, RoyaltiesV2Impl { // support ERC2981 bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; // The address of the creators of WizardDAO address public creatorsDAO; // An address who has permissions to mint Wizards address public minter; // The Wizards token URI descriptor IDescriptor public descriptor; // The Wizards token seeder ISeeder public seeder; // Whether the minter can be updated bool public isMinterLocked; // Whether the descriptor can be updated bool public isDescriptorLocked; // Whether the seeder can be updated bool public isSeederLocked; // The max supply wof wizards - 1 uint256 private supply; // The Wizards seeds mapping(uint256 => ISeeder.Seed) public seeds; // one of one tracker mapping(uint256 => uint8) private oneOfOneSupply; // The current wizard ID uint256 private _currentID; // The last wizard one of one ID uint48 public lastOneOfOneId; // IPFS content hash of contract-level metadata string private _contractURIHash = "QmYURRfzZH7UkUmffxYifyTbyQu5axg8tt9wG92wpSoigi"; // OpenSea's Proxy Registry IProxyRegistry public immutable proxyRegistry; // keep track of amont of one of ones to know when we upload more. // allows us to skip expensive one of one minting ops if we need have minted // all available one of ones uint256 public lastOneOfOneCount; /** * @notice Require that the minter has not been locked. */ modifier whenMinterNotLocked() { require(!isMinterLocked, "Minter is locked"); _; } /** * @notice Require that the descriptor has not been locked. */ modifier whenDescriptorNotLocked() { require(!isDescriptorLocked, "Descriptor is locked"); _; } /** * @notice Require that the seeder has not been locked. */ modifier whenSeederNotLocked() { require(!isSeederLocked, "Seeder is locked"); _; } /** * @notice Require that the sender is the creators DAO. */ modifier onlyCreatorsDAO() { require(msg.sender == creatorsDAO, "Sender is not the creators DAO"); _; } /** * @notice Require that the sender is the minter. */ modifier onlyMinter() { require(msg.sender == minter, "Sender is not the minter"); _; } constructor( address _creatorsDAO, address _minter, IDescriptor _descriptor, ISeeder _seeder, IProxyRegistry _proxyRegistry, uint256 _supply ) ERC721("Wizards", "WIZ") { creatorsDAO = _creatorsDAO; minter = _minter; descriptor = _descriptor; seeder = _seeder; proxyRegistry = _proxyRegistry; supply = _supply; } function setRoyalties( uint256 _tokenId, address payable _royaltiesReceipientAddress, uint96 _percentageBasisPoints ) public onlyOwner { LibPart.Part[] memory _royalties = new LibPart.Part[](1); _royalties[0].value = _percentageBasisPoints; _royalties[0].account = _royaltiesReceipientAddress; _saveRoyalties(_tokenId, _royalties); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, IERC165) returns (bool) { if (interfaceId == LibRoyaltiesV2._INTERFACE_ID_ROYALTIES) { return true; } if (interfaceId == type(IERC165).interfaceId) { return true; } if (interfaceId == _INTERFACE_ID_ERC2981) { return true; } return super.supportsInterface(interfaceId); } function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { LibPart.Part[] memory _royalties = royalties[_tokenId]; if (_royalties.length > 0) { // take a 10% royalty on secondary markets. return ( _royalties[0].account, (_salePrice * _royalties[0].value) / 10000 ); } return (address(0), 0); } /** * @notice The IPFS URI of contract-level metadata. */ function contractURI() public view returns (string memory) { return string(abi.encodePacked("ipfs://", _contractURIHash)); } /** * @notice Set the _contractURIHash. * @dev Only callable by the owner. */ function setContractURIHash(string memory newContractURIHash) external onlyOwner { _contractURIHash = newContractURIHash; } /** * @notice Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) public view override(IERC721, ERC721) returns (bool) { // Whitelist OpenSea proxy contract for easy trading. if (proxyRegistry.proxies(owner) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual returns (uint256) { return _currentID; } /** * @notice Mint a Wizard to the minter, along with a possible creators reward * Wizard. Creators reward Wizard are minted every 6 Wizards, starting at 0, * so that at the start of each auction one is minted to the creators, * until 54 creator Wizards have been minted. 1 wizard every day for 54 days. * @dev Call _mintTo with the to address(es). */ function mint() public override onlyMinter returns (uint256) { // we start minting for creators at 0 so _currentID should fall // below (6*54)-6 which is 318. if (_currentID <= 318 && _currentID % 6 == 0) { _mintTo(creatorsDAO, _currentID++, false, 0); } return _mintTo(minter, _currentID++, false, 0); } /** * @notice Mint a one of one Wizard to the minter. * @dev Call _mintTo with the to address(es) with the one of one id to mint. */ function mintOneOfOne(uint48 oneOfOneId) public override onlyMinter returns (uint256, bool) { uint256 oneCount = descriptor.oneOfOnesCount(); // validation; ensure a valid one of one index is requested require( uint256(oneOfOneId) < oneCount && oneOfOneId >= 0, "one of one does not exist" ); if (lastOneOfOneCount == oneCount) { // mint a generated wizard if we are out of one of ones. // skip expensive ops below. return (_mintTo(minter, _currentID++, false, 0), false); } // check if oneOfOneId > 0 in mapping if is 0 use it. if 1 then iterate from // 0 -> oneCount and find a oneOfOne with no value set. if we don't get any with a value set // then just mint a regular wizard uint8 oo = oneOfOneSupply[oneOfOneId]; if (oo == 0) { uint256 wizardId = _mintTo(minter, _currentID++, true, oneOfOneId); // set that we have minted a one of one at index oneOfOneSupply[oneOfOneId] = 1; lastOneOfOneId = oneOfOneId; return (wizardId, true); } // find a unused one of one to mint for (uint256 i = 0; i < oneCount; i++) { uint8 ofo = oneOfOneSupply[i]; if (ofo == 0) { uint256 wizardId = _mintTo( minter, _currentID++, true, uint48(i) ); oneOfOneSupply[i] = 1; lastOneOfOneId = uint48(i); return (wizardId, true); } } // we have spent all one of ones in the descriptor. record descriptor count // so next time we try to mint a one of one and it hasn't changed (we know // because we check oneOfOne supply above) we can skip the expensive map // iteration above. lastOneOfOneCount = oneCount; // mint a generated wizard if we are out of one of ones. return (_mintTo(minter, _currentID++, false, 0), false); } /** * @notice Burn a wizard. */ function burn(uint256 wizardId) public override onlyMinter { _burn(wizardId); emit WizardBurned(wizardId); } /** * @notice A distinct Uniform Resource Identifier (URI) for a given asset. * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { // if this throws an error then this wizard was burned or does not exist yet. require( _exists(tokenId), "WizardsToken: URI query for nonexistent token" ); return descriptor.tokenURI(tokenId, seeds[tokenId]); } /** * @notice Similar to `tokenURI`, but always serves a base64 encoded data URI * with the JSON contents directly inlined. */ function dataURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), "WizardsToken: URI query for nonexistent token" ); return descriptor.dataURI(tokenId, seeds[tokenId]); } /** * @notice Set the WizardsDAO address. * @dev Only callable by WizardsDAO. */ function setCreatorsDAO(address _creatorsDAO) external override onlyCreatorsDAO { creatorsDAO = _creatorsDAO; emit CreatorsDAOUpdated(_creatorsDAO); } /** * @notice Set the token minter. * @dev Only callable by the owner when not locked. */ function setMinter(address _minter) external override onlyOwner whenMinterNotLocked { minter = _minter; emit MinterUpdated(_minter); } /** * @notice Lock the minter. * @dev This cannot be reversed and is only callable by the owner when not locked. */ function lockMinter() external override onlyOwner whenMinterNotLocked { isMinterLocked = true; emit MinterLocked(); } /** * @notice Set the token URI descriptor. * @dev Only callable by the owner when not locked. */ function setDescriptor(IDescriptor _descriptor) external override onlyOwner whenDescriptorNotLocked { descriptor = _descriptor; emit DescriptorUpdated(_descriptor); } /** * @notice Lock the descriptor. * @dev This cannot be reversed and is only callable by the owner when not locked. */ function lockDescriptor() external override onlyOwner whenDescriptorNotLocked { isDescriptorLocked = true; emit DescriptorLocked(); } /** * @notice Set the token seeder. * @dev Only callable by the owner when not locked. */ function setSeeder(ISeeder _seeder) external override onlyOwner whenSeederNotLocked { seeder = _seeder; emit SeederUpdated(_seeder); } /** * @notice Lock the seeder. * @dev This cannot be reversed and is only callable by the owner when not locked. */ function lockSeeder() external override onlyOwner whenSeederNotLocked { isSeederLocked = true; emit SeederLocked(); } /** * @notice Set the wizard total supply. * @dev Only callable by the owner. */ function setSupply(uint256 _supply) external override onlyOwner { supply = _supply; emit SupplyUpdated(_supply); } /** * @notice Mint a Wizard with `wizardId` to the provided `to` address. */ function _mintTo( address to, uint256 wizardId, bool isOneOfOne, uint48 oneOfOneIndex ) internal returns (uint256) { // wizardId starts at 0 so should be less than 2000 require(wizardId < supply, "All wizards have been minted"); ISeeder.Seed memory seed = seeds[wizardId] = seeder.generateSeed( wizardId, descriptor, isOneOfOne, oneOfOneIndex ); _mint(owner(), to, wizardId); emit WizardCreated(wizardId, seed); return wizardId; } } // 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: GPL-3.0 /// @title Interface for Descriptor pragma solidity ^0.8.6; import { ISeeder } from '../seeder/ISeeder.sol'; interface IDescriptor { event PartsLocked(); event DataURIToggled(bool enabled); event BaseURIUpdated(string baseURI); function arePartsLocked() external returns (bool); function isDataURIEnabled() external returns (bool); function baseURI() external returns (string memory); function palettes(uint8 paletteIndex, uint256 colorIndex) external view returns (string memory); function addManyColorsToPalette(uint8 paletteIndex, string[] calldata newColors) external; function addColorToPalette(uint8 paletteIndex, string calldata color) external; function backgrounds(uint256 index) external view returns (string memory); function backgroundCount() external view returns (uint256); function addManyBackgrounds(string[] calldata backgrounds) external; function addBackground(string calldata background) external; function oneOfOnes(uint256 index) external view returns (bytes memory); function oneOfOnesCount() external view returns (uint256); function addOneOfOne(bytes calldata _oneOfOne) external; function addManyOneOfOnes(bytes[] calldata _oneOfOnes) external; function skins(uint256 index) external view returns (bytes memory); function skinsCount() external view returns (uint256); function addManySkins(bytes[] calldata skins) external; function addSkin(bytes calldata skin) external; function hats(uint256 index) external view returns (bytes memory); function hatsCount() external view returns (uint256); function addManyHats(bytes[] calldata hats) external; function addHat(bytes calldata hat) external; function clothes(uint256 index) external view returns (bytes memory); function clothesCount() external view returns (uint256); function addManyClothes(bytes[] calldata ears) external; function addClothes(bytes calldata ear) external; function mouths(uint256 index) external view returns (bytes memory); function mouthsCount() external view returns (uint256); function addManyMouths(bytes[] calldata mouths) external; function addMouth(bytes calldata mouth) external; function eyes(uint256 index) external view returns (bytes memory); function eyesCount() external view returns (uint256); function addManyEyes(bytes[] calldata eyes) external; function addEyes(bytes calldata eye) external; function accessory(uint256 index) external view returns (bytes memory); function accessoryCount() external view returns (uint256); function addManyAccessories(bytes[] calldata noses) external; function addAccessory(bytes calldata nose) external; function bgItems(uint256 index) external view returns (bytes memory); function bgItemsCount() external view returns (uint256); function addManyBgItems(bytes[] calldata noses) external; function addBgItem(bytes calldata nose) external; function lockParts() external; function toggleDataURIEnabled() external; function setBaseURI(string calldata baseURI) external; function tokenURI(uint256 tokenId, ISeeder.Seed memory seed) external view returns (string memory); function dataURI(uint256 tokenId, ISeeder.Seed memory seed) external view returns (string memory); function genericDataURI( string calldata name, string calldata description, ISeeder.Seed memory seed ) external view returns (string memory); function generateSVGImage(ISeeder.Seed memory seed) external view returns (string memory); } // SPDX-License-Identifier: GPL-3.0 /// @title Interface for Seeder pragma solidity ^0.8.6; import { IDescriptor } from '../descriptor/IDescriptor.sol'; // "Skin", "Cloth", "Eye", "Mouth", "Acc", "Item", "Hat" interface ISeeder { struct Seed { uint48 background; uint48 skin; uint48 clothes; uint48 eyes; uint48 mouth; uint48 accessory; uint48 bgItem; uint48 hat; bool oneOfOne; uint48 oneOfOneIndex; } function generateSeed(uint256 wizardId, IDescriptor descriptor, bool isOneOfOne, uint48 isOneOfOneIndex) external view returns (Seed memory); } // SPDX-License-Identifier: MIT /// @title ERC721 Token Implementation // LICENSE // ERC721.sol modifies OpenZeppelin's ERC721.sol: // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/6618f9f18424ade44116d0221719f4c93be6a078/contracts/token/ERC721/ERC721.sol // // ERC721.sol source code copyright OpenZeppelin licensed under the MIT License. // With modifications by Nounders DAO. // // // MODIFICATIONS: // `_safeMint` and `_mint` contain an additional `creator` argument and // emit two `Transfer` logs, rather than one. The first log displays the // transfer (mint) from `address(0)` to the `creator`. The second displays the // transfer from the `creator` to the `to` address. This enables correct // attribution on various NFT marketplaces. pragma solidity ^0.8.6; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol'; import '@openzeppelin/contracts/utils/Address.sol'; import '@openzeppelin/contracts/utils/Context.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; import '@openzeppelin/contracts/utils/introspection/ERC165.sol'; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), 'ERC721: balance query for the zero address'); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), 'ERC721: owner query for nonexistent token'); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), 'ERC721Metadata: URI query for nonexistent token'); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, 'ERC721: approval to current owner'); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), 'ERC721: approve caller is not owner nor approved for all' ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), 'ERC721: approved query for nonexistent token'); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), 'ERC721: approve to caller'); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), 'ERC721: transfer caller is not owner nor approved'); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), 'ERC721: transfer caller is not owner nor approved'); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), 'ERC721: transfer to non ERC721Receiver implementer'); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), 'ERC721: operator query for nonexistent token'); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId`, transfers it to `to`, and emits two log events - * 1. Credits the `minter` with the mint. * 2. Shows transfer from the `minter` 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 creator, address to, uint256 tokenId ) internal virtual { _safeMint(creator, 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 creator, address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(creator, to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), 'ERC721: transfer to non ERC721Receiver implementer' ); } /** * @dev Mints `tokenId`, transfers it to `to`, and emits two log events - * 1. Credits the `creator` with the mint. * 2. Shows transfer from the `creator` 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 creator, 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), creator, tokenId); emit Transfer(creator, to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, 'ERC721: transfer of token that is not own'); require(to != address(0), 'ERC721: transfer to the zero address'); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert('ERC721: transfer to non ERC721Receiver implementer'); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // 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 pragma solidity ^0.8.6; interface IProxyRegistry { function proxies(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /// @title Wizards ERC-721 token pragma solidity ^0.8.6; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import {ISeeder} from "./seeder/ISeeder.sol"; import {IDescriptor} from "./descriptor/IDescriptor.sol"; interface IWizardToken is IERC721 { event SupplyUpdated(uint256 indexed supply); event WizardCreated(uint256 indexed tokenId, ISeeder.Seed seed); event WizardBurned(uint256 indexed tokenId); event CreatorsDAOUpdated(address creatorsDAO); event MinterUpdated(address minter); event MinterLocked(); event DescriptorUpdated(IDescriptor descriptor); event DescriptorLocked(); event SeederUpdated(ISeeder seeder); event SeederLocked(); function mint() external returns (uint256); function mintOneOfOne(uint48 oneOfOneId) external returns (uint256, bool); function burn(uint256 tokenId) external; function dataURI(uint256 tokenId) external returns (string memory); function setCreatorsDAO(address creatorsDAO) external; function setMinter(address minter) external; function lockMinter() external; function setDescriptor(IDescriptor descriptor) external; function lockDescriptor() external; function setSeeder(ISeeder seeder) external; function lockSeeder() external; function setSupply(uint256 supply) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "./AbstractRoyalties.sol"; import "./RoyaltiesV2.sol"; contract RoyaltiesV2Impl is AbstractRoyalties, RoyaltiesV2 { function getRaribleV2Royalties(uint256 id) override external view returns (LibPart.Part[] memory) { return royalties[id]; } function _onRoyaltiesSet(uint256 _id, LibPart.Part[] memory _royalties) override internal { emit RoyaltiesSet(_id, _royalties); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; library LibPart { bytes32 public constant TYPE_HASH = keccak256("Part(address account,uint96 value)"); struct Part { address payable account; uint96 value; } function hash(Part memory part) internal pure returns (bytes32) { return keccak256(abi.encode(TYPE_HASH, part.account, part.value)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; library LibRoyaltiesV2 { /* * bytes4(keccak256('getRoyalties(LibAsset.AssetType)')) == 0x44c74bcc */ bytes4 constant _INTERFACE_ID_ROYALTIES = 0x44c74bcc; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts 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); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/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 pragma solidity ^0.8.6; import "./LibPart.sol"; abstract contract AbstractRoyalties { mapping (uint256 => LibPart.Part[]) public royalties; function _saveRoyalties(uint256 _id, LibPart.Part[] memory _royalties) internal { for (uint i = 0; i < _royalties.length; i++) { require(_royalties[i].account != address(0x0), "Recipient should be present"); require(_royalties[i].value != 0, "Royalty value should be positive"); royalties[_id].push(_royalties[i]); } _onRoyaltiesSet(_id, _royalties); } function _updateAccount(uint256 _id, address _from, address _to) internal { uint length = royalties[_id].length; for(uint i = 0; i < length; i++) { if (royalties[_id][i].account == _from) { royalties[_id][i].account = payable(address(uint160(_to))); } } } function _onRoyaltiesSet(uint256 _id, LibPart.Part[] memory _royalties) virtual internal; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "./LibPart.sol"; interface RoyaltiesV2 { event RoyaltiesSet(uint256 tokenId, LibPart.Part[] royalties); function getRaribleV2Royalties(uint256 id) external view returns (LibPart.Part[] memory); }
* @notice Mint a one of one Wizard to the minter. @dev Call _mintTo with the to address(es) with the one of one id to mint./ validation; ensure a valid one of one index is requested mint a generated wizard if we are out of one of ones. skip expensive ops below. set that we have minted a one of one at index find a unused one of one to mint
function mintOneOfOne(uint48 oneOfOneId) public override onlyMinter returns (uint256, bool) { uint256 oneCount = descriptor.oneOfOnesCount(); require( uint256(oneOfOneId) < oneCount && oneOfOneId >= 0, "one of one does not exist" ); if (lastOneOfOneCount == oneCount) { return (_mintTo(minter, _currentID++, false, 0), false); } if (oo == 0) { uint256 wizardId = _mintTo(minter, _currentID++, true, oneOfOneId); oneOfOneSupply[oneOfOneId] = 1; lastOneOfOneId = oneOfOneId; return (wizardId, true); } for (uint256 i = 0; i < oneCount; i++) { uint8 ofo = oneOfOneSupply[i]; if (ofo == 0) { uint256 wizardId = _mintTo( minter, _currentID++, true, uint48(i) ); oneOfOneSupply[i] = 1; lastOneOfOneId = uint48(i); return (wizardId, true); } } }
5,996,917
[ 1, 49, 474, 279, 1245, 434, 1245, 678, 13412, 358, 326, 1131, 387, 18, 225, 3049, 389, 81, 474, 774, 598, 326, 358, 1758, 12, 281, 13, 598, 326, 1245, 434, 1245, 612, 358, 312, 474, 18, 19, 3379, 31, 3387, 279, 923, 1245, 434, 1245, 770, 353, 3764, 312, 474, 279, 4374, 24204, 309, 732, 854, 596, 434, 1245, 434, 5945, 18, 2488, 19326, 6727, 5712, 18, 444, 716, 732, 1240, 312, 474, 329, 279, 1245, 434, 1245, 622, 770, 1104, 279, 10197, 1245, 434, 1245, 358, 312, 474, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 3335, 951, 3335, 12, 11890, 8875, 1245, 951, 3335, 548, 13, 203, 3639, 1071, 203, 3639, 3849, 203, 3639, 1338, 49, 2761, 203, 3639, 1135, 261, 11890, 5034, 16, 1426, 13, 203, 565, 288, 203, 3639, 2254, 5034, 1245, 1380, 273, 4950, 18, 476, 951, 1398, 281, 1380, 5621, 203, 203, 3639, 2583, 12, 203, 5411, 2254, 5034, 12, 476, 951, 3335, 548, 13, 411, 1245, 1380, 597, 1245, 951, 3335, 548, 1545, 374, 16, 203, 5411, 315, 476, 434, 1245, 1552, 486, 1005, 6, 203, 3639, 11272, 203, 203, 3639, 309, 261, 2722, 3335, 951, 3335, 1380, 422, 1245, 1380, 13, 288, 203, 5411, 327, 261, 67, 81, 474, 774, 12, 1154, 387, 16, 389, 2972, 734, 9904, 16, 629, 16, 374, 3631, 629, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 5161, 422, 374, 13, 288, 203, 5411, 2254, 5034, 24204, 548, 273, 389, 81, 474, 774, 12, 1154, 387, 16, 389, 2972, 734, 9904, 16, 638, 16, 1245, 951, 3335, 548, 1769, 203, 5411, 1245, 951, 3335, 3088, 1283, 63, 476, 951, 3335, 548, 65, 273, 404, 31, 203, 5411, 1142, 3335, 951, 3335, 548, 273, 1245, 951, 3335, 548, 31, 203, 5411, 327, 261, 31837, 548, 16, 638, 1769, 203, 3639, 289, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1245, 1380, 31, 277, 27245, 288, 203, 5411, 2254, 28, 434, 83, 273, 1245, 951, 3335, 3088, 1283, 63, 77, 15533, 203, 5411, 309, 261, 83, 617, 422, 374, 13, 2 ]
./full_match/137/0x2A9593907B0Fa448F7Cd657006ecE06Cc5E70E83/sources/POLYGON_USDT_Strat_Synapse.sol
called as part of strat migration. Sends all the available funds back to the vault.
function retireStrat() external { require(msg.sender == vault, "!vault"); ISynapseChef(chef).emergencyWithdraw(poolId, address(this)); ISynapseRouter(liquidityRouter).removeLiquidityOneToken(IERC20(underlyingAsset).balanceOf(address(this)), 3, 0, block.timestamp); uint256 wantBal = IERC20(want).balanceOf(address(this)); IERC20(want).transfer(vault, wantBal); }
4,710,783
[ 1, 11777, 487, 1087, 434, 609, 270, 6333, 18, 2479, 87, 777, 326, 2319, 284, 19156, 1473, 358, 326, 9229, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 325, 577, 1585, 270, 1435, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 9229, 16, 17528, 26983, 8863, 203, 203, 3639, 4437, 878, 28933, 39, 580, 74, 12, 343, 10241, 2934, 351, 24530, 1190, 9446, 12, 6011, 548, 16, 1758, 12, 2211, 10019, 203, 3639, 4437, 878, 28933, 8259, 12, 549, 372, 24237, 8259, 2934, 4479, 48, 18988, 24237, 3335, 1345, 12, 45, 654, 39, 3462, 12, 9341, 6291, 6672, 2934, 12296, 951, 12, 2867, 12, 2211, 13, 3631, 890, 16, 374, 16, 1203, 18, 5508, 1769, 203, 203, 3639, 2254, 5034, 2545, 38, 287, 273, 467, 654, 39, 3462, 12, 17369, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 467, 654, 39, 3462, 12, 17369, 2934, 13866, 12, 26983, 16, 2545, 38, 287, 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 ]
pragma solidity ^0.4.20; /* ETC Version: https://etherhub.io/addr/0xc2dc5e825faeb9bd274b61a2993f4f8949af4a21 */ contract BlackPearlETH { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } // 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) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won't reinitiate onlyAmbassadors = false; _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "Black Pearl ETH"; string public symbol = "MEDA"; uint8 constant public decimals = 18; uint8 constant internal entryFee_ = 20; // 20% Entry fee uint8 constant internal refferalFee_ = 15; // 15% Referral uint8 constant internal exitFee_ = 10; // 10% exit fee uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; // 250 Medaillions required for activation masternode uint256 public stakingRequirement = 250e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 50 ether; uint256 constant internal ambassadorQuota_ = 300 ether; // referral program mapping(address => uint256) internal referrals; mapping(address => bool) internal isUser; address[] public usersAddresses; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function BlackPearlETH() public { // N.O.T ambassadors_[0x9d71d8743f41987597e2ae3663cca36ca71024f4] = true; // T.T.U ambassadors_[0xC6D4a4A0bf0507749D4a23C9550A826207b5D94b] = true; // C.A ambassadors_[0x008ca4f1ba79d1a265617c6206d7884ee8108a78] = true; // R.A ambassadors_[0x41a21b264F9ebF6cF571D4543a5b3AB1c6bEd98C] = true; // J.K ambassadors_[0xc7F15d0238d207e19cce6bd6C0B85f343896F046] = true; // C.G ambassadors_[0xee54d208f62368b4effe176cb548a317dcae963f] = true; // P.X ambassadors_[0x074f21a36217d7615d0202faa926aefebb5a9999] = true; // S.Z ambassadors_[0x8c8F39b851ABF4455CFE5832a09B5E5ccEBD320f] = true; // Deployer administrators[msg.sender] = true; ambassadors_[msg.sender] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /* Converts all of caller's dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); } /* Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /* Withdraws all of the callers earnings. */ function withdraw() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /* Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /* Transfer tokens from the caller to a new holder. * No fee! */ 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(!onlyAmbassadors && _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 Transfer(_customerAddress, _toAddress, _amountOfTokens); // ERC20 return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * 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; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return this.balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } function referralsOf(address _customerAddress) public view returns(uint256) { return referrals[_customerAddress]; } function totalUsers() public view returns(uint256) { return usersAddresses.length; } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // 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 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() 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, entryFee_), 100); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ 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 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100); uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a Kekly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); if (isUser[_customerAddress] == false) { referrals[_referredBy]++; } } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } if (isUser[_customerAddress] == false ) { isUser[_customerAddress] = true; usersAddresses.push(_customerAddress); } // we can't give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; //really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @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; } }
* Function for the frontend to dynamically retrieve the price scaling of buy orders./
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; }
565,035
[ 1, 2083, 364, 326, 15442, 358, 18373, 4614, 326, 6205, 10612, 434, 30143, 11077, 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, 565, 445, 4604, 5157, 8872, 12, 11890, 5034, 389, 546, 822, 379, 774, 27223, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 12, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2254, 5034, 389, 2892, 350, 5839, 273, 14060, 10477, 18, 2892, 12, 9890, 10477, 18, 16411, 24899, 546, 822, 379, 774, 27223, 16, 1241, 14667, 67, 3631, 2130, 1769, 203, 3639, 2254, 5034, 389, 8066, 329, 41, 18664, 379, 273, 14060, 10477, 18, 1717, 24899, 546, 822, 379, 774, 27223, 16, 389, 2892, 350, 5839, 1769, 203, 3639, 2254, 5034, 389, 8949, 951, 5157, 273, 13750, 822, 379, 774, 5157, 67, 24899, 8066, 329, 41, 18664, 379, 1769, 203, 203, 3639, 327, 389, 8949, 951, 5157, 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 ]
pragma solidity >= 0.5.0 < 0.9.0; contract Election{ string public topic; uint public startTime; uint public endTime; struct Candidate{ // model a candidate uint id; string name; string partyName; uint voteCount; } struct Voter { address voterAddress; string name; bool voted; uint candidateId; } // for counting votes mapping(uint => uint) private voteCount; // store accounts that have voted mapping(address => Voter) private voters; // store candidate mapping(uint=> Candidate) public candidates; uint private votersCount; // store candidates Count uint public candidatesCount; event votedEvent ( uint indexed _candidateId ); constructor() public { startTime = block.timestamp; endTime = startTime + 2 minutes; topic = 'Who should be the Prime Minister(2022)?'; candidates[1] = Candidate(1, 'Rahul Gandhi','Congress',0); candidates[2] = Candidate(2, 'Narendra Modi','BJP',0); candidates[3] = Candidate(3, 'Arvind Kejriwal','AAP',0); candidates[4] = Candidate(4, 'Akhilesh Yadav','SP',0); candidatesCount = 4; } event voteCasted(address _voterAddress); function getCurrentVoter() public view returns (address, string memory, bool, uint) { Voter memory voter = voters[msg.sender]; return(voter.voterAddress, voter.name, voter.voted, voter.candidateId); } function getVoteCountFor(uint _candidateId) public view returns(uint, string memory) { return (voteCount[_candidateId], candidates[_candidateId].name); } // main voting function takes your selected candidate id and increments their vote count function vote(uint _candidateId) public { require(!voters[msg.sender].voted); voteCount[_candidateId]++; voters[msg.sender].voted = true; voters[msg.sender].candidateId = _candidateId; emit voteCasted(msg.sender); } function getWinningCandidate() public view returns (uint, string memory, uint) { uint maxVote = 0; uint maxVoteCandidateId = 0; for(uint i = 0; i<candidatesCount; i++) { if(maxVote < voteCount[i]) { maxVote = voteCount[i]; maxVoteCandidateId = i; } } return (maxVoteCandidateId, candidates[maxVoteCandidateId].name, maxVote); } } // 0x52C3087e23D22078D5a81A1FD17F2dE82D317613 // Election.deployed().then(function(i) { app=i;}) // web3.eth.getAccounts().then(function(acc){ accounts = acc }) // accounts[0] instead of web3.eth.accounts // truffle migrate --reset // truffle console // npm run dev
store accounts that have voted
mapping(address => Voter) private voters;
13,064,876
[ 1, 2233, 9484, 716, 1240, 331, 16474, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 12, 2867, 516, 776, 20005, 13, 3238, 331, 352, 414, 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 ]
./full_match/4/0x870F471A048a3E7748db666e0458beC5C003a24e/sources/Aff_flat.sol
* @dev See {IERC721-safeTransferFrom}./
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); }
12,359,123
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 17, 4626, 5912, 1265, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 915, 4183, 5912, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 1147, 548, 13, 1071, 5024, 3849, 288, 203, 4626, 5912, 1265, 12, 2080, 16, 358, 16, 1147, 548, 16, 1408, 1769, 203, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xbfD7d91eDD9BFF8774543B3eAf953De989e76CcA/sources/contracts/SaldDrop.sol
@dev The active conditions for claiming tokens.
contract SaldDrop is ERC2771Context, Ownable { using SafeERC20 for IERC20; IERC20 public erc20ContractAddress; ClaimConditionList public claimCondition; pragma solidity ^0.8.0; constructor(address _trustedForwarder) ERC2771Context(_trustedForwarder) {} struct ClaimCondition { address receiverAddress; uint256 maxClaimable; uint256 claimedAmount; uint256 claimFrom; } struct ClaimConditionList { uint256 currentStartId; uint256 count; mapping(uint256 => ClaimCondition) conditions; mapping(uint256 => mapping(address => uint256)) supplyClaimedByWallet; } event TokensClaimed( uint256 indexed claimConditionIndex, address indexed receiver, uint256 amount ); event ClaimConditionsUpdated(ClaimCondition[]); mapping(bytes32 => mapping(address => uint256)) private claimedAmount; function setContractAddress(IERC20 _contractAddress) external onlyOwner { erc20ContractAddress = _contractAddress; } function getErc20Balance() public view returns (uint256) { return erc20ContractAddress.balanceOf(address(this)); } function _msgSender() internal view virtual override(ERC2771Context, Context) returns (address sender) { return ERC2771Context._msgSender(); } function _msgData() internal view virtual override(ERC2771Context, Context) returns (bytes calldata) { return ERC2771Context._msgData(); } function claim(uint _amount) external { uint256 activeConditionId = getActiveClaimConditionId(); ClaimCondition memory currentClaimPhase = claimCondition.conditions[ activeConditionId ]; if ( currentClaimPhase.claimedAmount + _amount > currentClaimPhase.maxClaimable ) { revert("Exceeds claimable amount."); } if (currentClaimPhase.claimFrom > block.timestamp) { revert("Claim time not reached."); } require( currentClaimPhase.receiverAddress != address(0), "Address not in whitelist" ); uint256 claimableAmount = currentClaimPhase.maxClaimable - currentClaimPhase.claimedAmount; require(claimableAmount > 0, "No tokens claimable"); require(_amount <= claimableAmount, "Exceeds claimable amount"); require( _amount <= erc20ContractAddress.balanceOf(address(this)), "Insufficient contract balance" ); claimCondition.supplyClaimedByWallet[activeConditionId][ _claimMsgSender() ] += _amount; emit TokensClaimed(activeConditionId, _claimMsgSender(), _amount); } function claim(uint _amount) external { uint256 activeConditionId = getActiveClaimConditionId(); ClaimCondition memory currentClaimPhase = claimCondition.conditions[ activeConditionId ]; if ( currentClaimPhase.claimedAmount + _amount > currentClaimPhase.maxClaimable ) { revert("Exceeds claimable amount."); } if (currentClaimPhase.claimFrom > block.timestamp) { revert("Claim time not reached."); } require( currentClaimPhase.receiverAddress != address(0), "Address not in whitelist" ); uint256 claimableAmount = currentClaimPhase.maxClaimable - currentClaimPhase.claimedAmount; require(claimableAmount > 0, "No tokens claimable"); require(_amount <= claimableAmount, "Exceeds claimable amount"); require( _amount <= erc20ContractAddress.balanceOf(address(this)), "Insufficient contract balance" ); claimCondition.supplyClaimedByWallet[activeConditionId][ _claimMsgSender() ] += _amount; emit TokensClaimed(activeConditionId, _claimMsgSender(), _amount); } function claim(uint _amount) external { uint256 activeConditionId = getActiveClaimConditionId(); ClaimCondition memory currentClaimPhase = claimCondition.conditions[ activeConditionId ]; if ( currentClaimPhase.claimedAmount + _amount > currentClaimPhase.maxClaimable ) { revert("Exceeds claimable amount."); } if (currentClaimPhase.claimFrom > block.timestamp) { revert("Claim time not reached."); } require( currentClaimPhase.receiverAddress != address(0), "Address not in whitelist" ); uint256 claimableAmount = currentClaimPhase.maxClaimable - currentClaimPhase.claimedAmount; require(claimableAmount > 0, "No tokens claimable"); require(_amount <= claimableAmount, "Exceeds claimable amount"); require( _amount <= erc20ContractAddress.balanceOf(address(this)), "Insufficient contract balance" ); claimCondition.supplyClaimedByWallet[activeConditionId][ _claimMsgSender() ] += _amount; emit TokensClaimed(activeConditionId, _claimMsgSender(), _amount); } claimCondition.conditions[activeConditionId].claimedAmount += _amount; erc20ContractAddress.safeTransfer(_claimMsgSender(), _amount); function setClaimConditions( ClaimCondition[] calldata _conditions ) external onlyOwner { uint256 existingStartIndex = claimCondition.currentStartId; uint256 existingPhaseCount = claimCondition.count; uint256 newStartIndex = existingStartIndex; claimCondition.count = _conditions.length; claimCondition.currentStartId = newStartIndex; uint256 lastConditionStartTimestamp; for (uint256 i = 0; i < _conditions.length; i++) { require( i == 0 || lastConditionStartTimestamp < _conditions[i].claimFrom, "ST" ); uint256 supplyClaimedAlready = claimCondition .conditions[newStartIndex + i] .claimedAmount; if (supplyClaimedAlready > _conditions[i].maxClaimable) { revert("max supply claimed"); } claimCondition.conditions[newStartIndex + i] = _conditions[i]; claimCondition .conditions[newStartIndex + i] .claimedAmount = supplyClaimedAlready; lastConditionStartTimestamp = _conditions[i].claimFrom; } if (existingPhaseCount > _conditions.length) { for (uint256 i = _conditions.length; i < existingPhaseCount; i++) { delete claimCondition.conditions[newStartIndex + i]; } } emit ClaimConditionsUpdated(_conditions); } function setClaimConditions( ClaimCondition[] calldata _conditions ) external onlyOwner { uint256 existingStartIndex = claimCondition.currentStartId; uint256 existingPhaseCount = claimCondition.count; uint256 newStartIndex = existingStartIndex; claimCondition.count = _conditions.length; claimCondition.currentStartId = newStartIndex; uint256 lastConditionStartTimestamp; for (uint256 i = 0; i < _conditions.length; i++) { require( i == 0 || lastConditionStartTimestamp < _conditions[i].claimFrom, "ST" ); uint256 supplyClaimedAlready = claimCondition .conditions[newStartIndex + i] .claimedAmount; if (supplyClaimedAlready > _conditions[i].maxClaimable) { revert("max supply claimed"); } claimCondition.conditions[newStartIndex + i] = _conditions[i]; claimCondition .conditions[newStartIndex + i] .claimedAmount = supplyClaimedAlready; lastConditionStartTimestamp = _conditions[i].claimFrom; } if (existingPhaseCount > _conditions.length) { for (uint256 i = _conditions.length; i < existingPhaseCount; i++) { delete claimCondition.conditions[newStartIndex + i]; } } emit ClaimConditionsUpdated(_conditions); } function setClaimConditions( ClaimCondition[] calldata _conditions ) external onlyOwner { uint256 existingStartIndex = claimCondition.currentStartId; uint256 existingPhaseCount = claimCondition.count; uint256 newStartIndex = existingStartIndex; claimCondition.count = _conditions.length; claimCondition.currentStartId = newStartIndex; uint256 lastConditionStartTimestamp; for (uint256 i = 0; i < _conditions.length; i++) { require( i == 0 || lastConditionStartTimestamp < _conditions[i].claimFrom, "ST" ); uint256 supplyClaimedAlready = claimCondition .conditions[newStartIndex + i] .claimedAmount; if (supplyClaimedAlready > _conditions[i].maxClaimable) { revert("max supply claimed"); } claimCondition.conditions[newStartIndex + i] = _conditions[i]; claimCondition .conditions[newStartIndex + i] .claimedAmount = supplyClaimedAlready; lastConditionStartTimestamp = _conditions[i].claimFrom; } if (existingPhaseCount > _conditions.length) { for (uint256 i = _conditions.length; i < existingPhaseCount; i++) { delete claimCondition.conditions[newStartIndex + i]; } } emit ClaimConditionsUpdated(_conditions); } function setClaimConditions( ClaimCondition[] calldata _conditions ) external onlyOwner { uint256 existingStartIndex = claimCondition.currentStartId; uint256 existingPhaseCount = claimCondition.count; uint256 newStartIndex = existingStartIndex; claimCondition.count = _conditions.length; claimCondition.currentStartId = newStartIndex; uint256 lastConditionStartTimestamp; for (uint256 i = 0; i < _conditions.length; i++) { require( i == 0 || lastConditionStartTimestamp < _conditions[i].claimFrom, "ST" ); uint256 supplyClaimedAlready = claimCondition .conditions[newStartIndex + i] .claimedAmount; if (supplyClaimedAlready > _conditions[i].maxClaimable) { revert("max supply claimed"); } claimCondition.conditions[newStartIndex + i] = _conditions[i]; claimCondition .conditions[newStartIndex + i] .claimedAmount = supplyClaimedAlready; lastConditionStartTimestamp = _conditions[i].claimFrom; } if (existingPhaseCount > _conditions.length) { for (uint256 i = _conditions.length; i < existingPhaseCount; i++) { delete claimCondition.conditions[newStartIndex + i]; } } emit ClaimConditionsUpdated(_conditions); } function setClaimConditions( ClaimCondition[] calldata _conditions ) external onlyOwner { uint256 existingStartIndex = claimCondition.currentStartId; uint256 existingPhaseCount = claimCondition.count; uint256 newStartIndex = existingStartIndex; claimCondition.count = _conditions.length; claimCondition.currentStartId = newStartIndex; uint256 lastConditionStartTimestamp; for (uint256 i = 0; i < _conditions.length; i++) { require( i == 0 || lastConditionStartTimestamp < _conditions[i].claimFrom, "ST" ); uint256 supplyClaimedAlready = claimCondition .conditions[newStartIndex + i] .claimedAmount; if (supplyClaimedAlready > _conditions[i].maxClaimable) { revert("max supply claimed"); } claimCondition.conditions[newStartIndex + i] = _conditions[i]; claimCondition .conditions[newStartIndex + i] .claimedAmount = supplyClaimedAlready; lastConditionStartTimestamp = _conditions[i].claimFrom; } if (existingPhaseCount > _conditions.length) { for (uint256 i = _conditions.length; i < existingPhaseCount; i++) { delete claimCondition.conditions[newStartIndex + i]; } } emit ClaimConditionsUpdated(_conditions); } function getActiveClaimConditionId() public view returns (uint256) { for ( uint256 i = claimCondition.currentStartId + claimCondition.count; i > claimCondition.currentStartId; i-- ) { if (block.timestamp >= claimCondition.conditions[i - 1].claimFrom) { return i - 1; } } revert("Condition"); } function getActiveClaimConditionId() public view returns (uint256) { for ( uint256 i = claimCondition.currentStartId + claimCondition.count; i > claimCondition.currentStartId; i-- ) { if (block.timestamp >= claimCondition.conditions[i - 1].claimFrom) { return i - 1; } } revert("Condition"); } function getActiveClaimConditionId() public view returns (uint256) { for ( uint256 i = claimCondition.currentStartId + claimCondition.count; i > claimCondition.currentStartId; i-- ) { if (block.timestamp >= claimCondition.conditions[i - 1].claimFrom) { return i - 1; } } revert("Condition"); } function getClaimConditionById( uint256 _conditionId ) external view returns (ClaimCondition memory condition) { condition = claimCondition.conditions[_conditionId]; } function getSupplyClaimedByWallet( uint256 _conditionId, address _claimer ) public view returns (uint256 supplyClaimedByWallet) { supplyClaimedByWallet = claimCondition.supplyClaimedByWallet[ _conditionId ][_claimer]; } function _claimMsgSender() internal view returns (address) { return msg.sender; } }
1,882,812
[ 1, 1986, 2695, 4636, 364, 7516, 310, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 348, 287, 72, 7544, 353, 4232, 39, 22, 4700, 21, 1042, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 203, 565, 467, 654, 39, 3462, 1071, 6445, 71, 3462, 8924, 1887, 31, 203, 203, 565, 18381, 3418, 682, 1071, 7516, 3418, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 3885, 12, 2867, 389, 25247, 30839, 13, 4232, 39, 22, 4700, 21, 1042, 24899, 25247, 30839, 13, 2618, 203, 565, 1958, 18381, 3418, 288, 203, 3639, 1758, 5971, 1887, 31, 203, 3639, 2254, 5034, 943, 9762, 429, 31, 203, 3639, 2254, 5034, 7516, 329, 6275, 31, 203, 3639, 2254, 5034, 7516, 1265, 31, 203, 565, 289, 203, 203, 565, 1958, 18381, 3418, 682, 288, 203, 3639, 2254, 5034, 783, 1685, 548, 31, 203, 3639, 2254, 5034, 1056, 31, 203, 3639, 2874, 12, 11890, 5034, 516, 18381, 3418, 13, 4636, 31, 203, 3639, 2874, 12, 11890, 5034, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 14467, 9762, 18696, 16936, 31, 203, 565, 289, 203, 203, 203, 565, 871, 13899, 9762, 329, 12, 203, 3639, 2254, 5034, 8808, 7516, 3418, 1016, 16, 203, 3639, 1758, 8808, 5971, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 11272, 203, 565, 871, 18381, 8545, 7381, 12, 9762, 3418, 8526, 1769, 203, 203, 565, 2874, 12, 3890, 1578, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 7516, 329, 6275, 31, 203, 565, 445, 444, 8924, 1887, 12, 45, 654, 39, 2 ]
// File: contracts/libs/openzeppelin_upgradable_v2_5_0/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: contracts/libs/openzeppelin_upgradable_v2_5_0/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/libs/openzeppelin_upgradable_v2_5_0/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } // File: contracts/libs/SafeMath.sol pragma solidity ^0.5.5; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } /** * @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: contracts/interfaces/ERC20Advanced.sol pragma solidity ^0.5.5; /** * @title ERC20 Advanced interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface ERC20Advanced { function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address from, address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/interfaces/ERC20Basic.sol pragma solidity ^0.5.5; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ interface ERC20Basic { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: contracts/interfaces/ERC20Standard.sol pragma solidity ^0.5.5; /** * @title ERC20Standard * @dev Full ERC20 interface */ contract ERC20Standard is ERC20Basic, ERC20Advanced {} // File: contracts/tokenDistribution/TokenDistribution.sol /** * @title TokenDistribution * @author @Ola, @ziweidream * @notice This contract allows Investors to claim tokens based on a future token WITHDRAWAL date, * and an amount of ether they contributed and bonus percentage of KTY allocations based on * amount of Ether contributed. */ pragma solidity ^0.5.5; contract TokenDistribution is Ownable { using SafeMath for uint256; /* GENERAL VARIABLES */ /* ============================================================================================================== */ ERC20Standard public token; // ERC20Token contract variable uint256 constant internal base18 = 1000000000000000000; uint256 public standardRate; uint256 public percentBonus; // Percentage Bonus uint256 public withdrawDate; // Withdraw Date uint256 public totalNumberOfInvestments; // total number of investments uint256 public totalEtherInvested; // total amount of ethers invested from all investments // details of an Investment struct Investment { address investAddr; uint256 ethAmount; bool hasClaimed; uint256 principalClaimed; uint256 bonusClaimed; uint256 claimTime; } // mapping investment number to the details of the investment mapping(uint256 => Investment) public investments; // mapping investment address to the investment ID of all the investments made by this address mapping(address => uint256[]) public investmentIDs; uint256 private unlocked; /* MODIFIERS */ /* ============================================================================================================== */ modifier lock() { require(unlocked == 1, 'Locked'); unlocked = 0; _; unlocked = 1; } /* INITIALIZER */ /* ============================================================================================================== */ function initialize ( address[] calldata _investors, uint256[] calldata _ethAmounts, ERC20Standard _erc20Token, uint256 _withdrawDate, uint256 _standardRate, uint256 _percentBonus ) external initializer { Ownable.initialize(_msgSender()); // set investments addInvestments(_investors, _ethAmounts); // set ERC20Token contract variable setERC20Token(_erc20Token); // Set withdraw date withdrawDate = _withdrawDate; standardRate = _standardRate; // Set percentage bonus percentBonus = _percentBonus; //Reentrancy lock unlocked = 1; } /* EVENTS */ /* ============================================================================================================== */ event WithDrawn( address indexed investor, uint256 indexed investmentID, uint256 principal, uint256 bonus, uint256 withdrawTime ); /* YIELD FARMING FUNCTIONS */ /* ============================================================================================================== */ /** * @notice Withdraw tokens * @param investmentID uint256 investment ID of the investment for which the bonus tokens are distributed * @return bool true if the withdraw is successful */ function withdraw(uint256 investmentID) external lock returns (bool) { require(investments[investmentID].investAddr == msg.sender, "You are not the investor of this investment"); require(block.timestamp >= withdrawDate, "Can only withdraw after withdraw date"); require(!investments[investmentID].hasClaimed, "Tokens already withdrawn for this investment"); require(investments[investmentID].ethAmount > 0, "0 ether in this investment"); // get the ether amount of this investment uint256 _ethAmount = investments[investmentID].ethAmount; (uint256 _principal, uint256 _bonus, uint256 _principalAndBonus) = calculatePrincipalAndBonus(_ethAmount); _updateWithdraw(investmentID, _principal, _bonus); // transfer tokens to this investor require(token.transfer(msg.sender, _principalAndBonus), "Fail to transfer tokens"); emit WithDrawn(msg.sender, investmentID, _principal, _bonus, block.timestamp); return true; } /* SETTER FUNCTIONS */ /* ============================================================================================================== */ /** * @dev Add new investments * @dev This function can only be carreid out by the owner of this contract. */ function addInvestments(address[] memory _investors, uint256[] memory _ethAmounts) public onlyOwner { require(_investors.length == _ethAmounts.length, "The number of investing addresses should equal the number of ether amounts"); for (uint256 i = 0; i < _investors.length; i++) { addInvestment(_investors[i], _ethAmounts[i]); } } /** * @dev Set ERC20Token contract * @dev This function can only be carreid out by the owner of this contract. */ function setERC20Token(ERC20Standard _erc20Token) public onlyOwner { token = _erc20Token; } /** * @dev Set standard rate. Standard rate is amplified 10**18 times for float precision * @dev This function can only be carreid out by the owner of this contract. */ function setStandardRate(uint256 _standardRate) public onlyOwner { standardRate = _standardRate; } /** * @dev Set percentage bonus. Percentage bonus is amplified 10**18 times for float precision * @dev This function can only be carreid out by the owner of this contract. */ function setPercentBonus(uint256 _percentBonus) public onlyOwner { percentBonus = _percentBonus; } /** * @notice This function transfers tokens out of this contract to a new address * @dev This function is used to transfer unclaimed KittieFightToken to a new address, * or transfer other tokens erroneously tranferred to this contract back to their original owner * @dev This function can only be carreid out by the owner of this contract. */ function returnTokens(address _token, uint256 _amount, address _newAddress) external onlyOwner { require(block.timestamp >= withdrawDate.add(7 * 24 * 60 * 60), "Cannot return any token within 7 days of withdraw date"); uint256 balance = ERC20Standard(_token).balanceOf(address(this)); require(_amount <= balance, "Exceeds balance"); require(ERC20Standard(_token).transfer(_newAddress, _amount), "Fail to transfer tokens"); } /** * @notice Set withdraw date for the token * @param _withdrawDate uint256 withdraw date for the token * @dev This function can only be carreid out by the owner of this contract. */ function setWithdrawDate(uint256 _withdrawDate) public onlyOwner { withdrawDate = _withdrawDate; } /* GETTER FUNCTIONS */ /* ============================================================================================================== */ /** * @return true and 0 if it is time to withdraw, false and time until withdraw if it is not the time to withdraw yet */ function canWithdraw() public view returns (bool, uint256) { if (block.timestamp >= withdrawDate) { return (true, 0); } else { return (false, withdrawDate.sub(block.timestamp)); } } /** * @return uint256 bonus tokens calculated for the amount of ether specified */ function calculatePrincipalAndBonus(uint256 _ether) public view returns (uint256, uint256, uint256) { uint256 principal = _ether.mul(standardRate).div(base18); uint256 bonus = principal.mul(percentBonus).div(base18); uint256 principalAndBonus = principal.add(bonus); return (principal, bonus, principalAndBonus); } /** * @return address an array of the ID of each investment belonging to the investor */ function getInvestmentIDs(address _investAddr) external view returns (uint256[] memory) { return investmentIDs[_investAddr]; } /** * @return the details of an investment associated with an investment ID, including the address * of the investor, the amount of ether invested in this investment, whether bonus tokens * have been claimed for this investment, the amount of bonus tokens already claimed for * this investment(0 if bonus tokens are not claimed yet), the unix time when the bonus tokens * have been claimed(0 if bonus tokens are not claimed yet) */ function getInvestment(uint256 _investmentID) external view returns(address _investAddr, uint256 _ethAmount, bool _hasClaimed, uint256 _principalClaimed, uint256 _bonusClaimed, uint256 _claimTime) { _investAddr = investments[_investmentID].investAddr; _ethAmount = investments[_investmentID].ethAmount; _hasClaimed = investments[_investmentID].hasClaimed; _principalClaimed = investments[_investmentID].principalClaimed; _bonusClaimed = investments[_investmentID].bonusClaimed; _claimTime = investments[_investmentID].claimTime; } /* PRIVATE FUNCTIONS */ /* ============================================================================================================== */ /** * @param _investmentID uint256 investment ID of the investment for which tokens are withdrawn * @param _bonus uint256 tokens distributed to this investor * @dev this function updates the storage upon successful withdraw of tokens. */ function _updateWithdraw(uint256 _investmentID, uint256 _principal, uint256 _bonus) private { investments[_investmentID].hasClaimed = true; investments[_investmentID].principalClaimed = _principal; investments[_investmentID].bonusClaimed = _bonus; investments[_investmentID].claimTime = block.timestamp; investments[_investmentID].ethAmount = 0; } /** * @dev Add one new investment */ function addInvestment(address _investor, uint256 _eth) private { uint256 investmentID = totalNumberOfInvestments.add(1); investments[investmentID].investAddr = _investor; investments[investmentID].ethAmount = _eth; totalEtherInvested = totalEtherInvested.add(_eth); totalNumberOfInvestments = investmentID; investmentIDs[_investor].push(investmentID); } }
details of an Investment
contract TokenDistribution is Ownable { using SafeMath for uint256; uint256 constant internal base18 = 1000000000000000000; uint256 public standardRate; contract ERC20Standard is ERC20Basic, ERC20Advanced {} pragma solidity ^0.5.5; struct Investment { address investAddr; uint256 ethAmount; bool hasClaimed; uint256 principalClaimed; uint256 bonusClaimed; uint256 claimTime; } uint256 private unlocked; mapping(uint256 => Investment) public investments; mapping(address => uint256[]) public investmentIDs; modifier lock() { require(unlocked == 1, 'Locked'); unlocked = 0; _; unlocked = 1; } function initialize ( address[] calldata _investors, uint256[] calldata _ethAmounts, ERC20Standard _erc20Token, uint256 _withdrawDate, uint256 _standardRate, uint256 _percentBonus ) external initializer { Ownable.initialize(_msgSender()); addInvestments(_investors, _ethAmounts); setERC20Token(_erc20Token); withdrawDate = _withdrawDate; standardRate = _standardRate; percentBonus = _percentBonus; unlocked = 1; } address indexed investor, uint256 indexed investmentID, uint256 principal, uint256 bonus, uint256 withdrawTime ); event WithDrawn( function withdraw(uint256 investmentID) external lock returns (bool) { require(investments[investmentID].investAddr == msg.sender, "You are not the investor of this investment"); require(block.timestamp >= withdrawDate, "Can only withdraw after withdraw date"); require(!investments[investmentID].hasClaimed, "Tokens already withdrawn for this investment"); require(investments[investmentID].ethAmount > 0, "0 ether in this investment"); uint256 _ethAmount = investments[investmentID].ethAmount; (uint256 _principal, uint256 _bonus, uint256 _principalAndBonus) = calculatePrincipalAndBonus(_ethAmount); _updateWithdraw(investmentID, _principal, _bonus); require(token.transfer(msg.sender, _principalAndBonus), "Fail to transfer tokens"); emit WithDrawn(msg.sender, investmentID, _principal, _bonus, block.timestamp); return true; } function addInvestments(address[] memory _investors, uint256[] memory _ethAmounts) public onlyOwner { require(_investors.length == _ethAmounts.length, "The number of investing addresses should equal the number of ether amounts"); for (uint256 i = 0; i < _investors.length; i++) { addInvestment(_investors[i], _ethAmounts[i]); } } function addInvestments(address[] memory _investors, uint256[] memory _ethAmounts) public onlyOwner { require(_investors.length == _ethAmounts.length, "The number of investing addresses should equal the number of ether amounts"); for (uint256 i = 0; i < _investors.length; i++) { addInvestment(_investors[i], _ethAmounts[i]); } } function setERC20Token(ERC20Standard _erc20Token) public onlyOwner { token = _erc20Token; } function setStandardRate(uint256 _standardRate) public onlyOwner { standardRate = _standardRate; } function setPercentBonus(uint256 _percentBonus) public onlyOwner { percentBonus = _percentBonus; } function returnTokens(address _token, uint256 _amount, address _newAddress) external onlyOwner { require(block.timestamp >= withdrawDate.add(7 * 24 * 60 * 60), "Cannot return any token within 7 days of withdraw date"); uint256 balance = ERC20Standard(_token).balanceOf(address(this)); require(_amount <= balance, "Exceeds balance"); require(ERC20Standard(_token).transfer(_newAddress, _amount), "Fail to transfer tokens"); } function setWithdrawDate(uint256 _withdrawDate) public onlyOwner { withdrawDate = _withdrawDate; } function canWithdraw() public view returns (bool, uint256) { if (block.timestamp >= withdrawDate) { return (true, 0); return (false, withdrawDate.sub(block.timestamp)); } } function canWithdraw() public view returns (bool, uint256) { if (block.timestamp >= withdrawDate) { return (true, 0); return (false, withdrawDate.sub(block.timestamp)); } } } else { function calculatePrincipalAndBonus(uint256 _ether) public view returns (uint256, uint256, uint256) { uint256 principal = _ether.mul(standardRate).div(base18); uint256 bonus = principal.mul(percentBonus).div(base18); uint256 principalAndBonus = principal.add(bonus); return (principal, bonus, principalAndBonus); } function getInvestmentIDs(address _investAddr) external view returns (uint256[] memory) { return investmentIDs[_investAddr]; } function getInvestment(uint256 _investmentID) external view returns(address _investAddr, uint256 _ethAmount, bool _hasClaimed, uint256 _principalClaimed, uint256 _bonusClaimed, uint256 _claimTime) { _investAddr = investments[_investmentID].investAddr; _ethAmount = investments[_investmentID].ethAmount; _hasClaimed = investments[_investmentID].hasClaimed; _principalClaimed = investments[_investmentID].principalClaimed; _bonusClaimed = investments[_investmentID].bonusClaimed; _claimTime = investments[_investmentID].claimTime; } function _updateWithdraw(uint256 _investmentID, uint256 _principal, uint256 _bonus) private { investments[_investmentID].hasClaimed = true; investments[_investmentID].principalClaimed = _principal; investments[_investmentID].bonusClaimed = _bonus; investments[_investmentID].claimTime = block.timestamp; investments[_investmentID].ethAmount = 0; } function addInvestment(address _investor, uint256 _eth) private { uint256 investmentID = totalNumberOfInvestments.add(1); investments[investmentID].investAddr = _investor; investments[investmentID].ethAmount = _eth; totalEtherInvested = totalEtherInvested.add(_eth); totalNumberOfInvestments = investmentID; investmentIDs[_investor].push(investmentID); } }
15,039,915
[ 1, 6395, 434, 392, 5454, 395, 475, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3155, 9003, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 203, 203, 565, 2254, 5034, 5381, 2713, 1026, 2643, 273, 2130, 12648, 12648, 31, 203, 203, 565, 2254, 5034, 1071, 4529, 4727, 31, 203, 203, 203, 203, 16351, 4232, 39, 3462, 8336, 353, 4232, 39, 3462, 8252, 16, 4232, 39, 3462, 23618, 2618, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 25, 18, 25, 31, 203, 565, 1958, 5454, 395, 475, 288, 203, 3639, 1758, 2198, 395, 3178, 31, 203, 3639, 2254, 5034, 13750, 6275, 31, 203, 3639, 1426, 711, 9762, 329, 31, 203, 3639, 2254, 5034, 8897, 9762, 329, 31, 203, 3639, 2254, 5034, 324, 22889, 9762, 329, 31, 203, 3639, 2254, 5034, 7516, 950, 31, 203, 565, 289, 203, 203, 203, 203, 565, 2254, 5034, 3238, 25966, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 5454, 395, 475, 13, 1071, 2198, 395, 1346, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 63, 5717, 1071, 2198, 395, 475, 5103, 31, 203, 565, 9606, 2176, 1435, 288, 203, 3639, 2583, 12, 318, 15091, 422, 404, 16, 296, 8966, 8284, 203, 3639, 25966, 273, 374, 31, 203, 3639, 389, 31, 203, 3639, 25966, 273, 404, 31, 203, 565, 289, 6647, 203, 203, 565, 445, 4046, 203, 565, 261, 203, 3639, 1758, 8526, 745, 892, 389, 5768, 395, 1383, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 389, 546, 6275, 87, 16, 203, 3639, 4232, 39, 3462, 8336, 389, 12610, 3462, 1345, 16, 203, 3639, 2 ]
./partial_match/1/0xB10daee1FCF62243aE27776D7a92D39dC8740f95/sources/src/abstracts/SablierV2Lockup.sol
//*/ @inheritdoc ISablierV2Lockup//*/ @dev Contract that generates the non-fungible token URI.//*/ @param initialAdmin The address of the initial contract admin. @param initialComptroller The address of the initial comptroller. @param initialNFTDescriptor The address of the initial NFT descriptor.
{ _nftDescriptor = initialNFTDescriptor; } MODIFIERS
9,308,369
[ 1, 28111, 632, 10093, 4437, 378, 9800, 58, 22, 2531, 416, 28111, 225, 13456, 716, 6026, 326, 1661, 17, 12125, 75, 1523, 1147, 3699, 18, 28111, 225, 2172, 4446, 1021, 1758, 434, 326, 2172, 6835, 3981, 18, 225, 2172, 799, 337, 1539, 1021, 1758, 434, 326, 2172, 532, 337, 1539, 18, 225, 2172, 50, 4464, 3187, 1021, 1758, 434, 326, 2172, 423, 4464, 4950, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 3639, 389, 82, 1222, 3187, 273, 2172, 50, 4464, 3187, 31, 203, 565, 289, 203, 203, 4766, 1377, 8663, 10591, 55, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x19748a349a0c55CA10FeCcD426081212DE2D19E4/sources/contracts/alloyx/core/AlloyxVault.sol
* @notice Get total the regular staker gain/
function getRegularStakerGainInVault() public view returns (uint256) { (, , uint256 regularStakerGain) = getTotalInvestorUsdcValueAndAdditionalGains(); return regularStakerGain.add(preRegularStakerGain); }
3,069,283
[ 1, 967, 2078, 326, 6736, 384, 6388, 17527, 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, 225, 445, 336, 17974, 510, 6388, 43, 530, 382, 12003, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 261, 16, 269, 2254, 5034, 6736, 510, 6388, 43, 530, 13, 273, 12831, 3605, 395, 280, 3477, 7201, 620, 1876, 10552, 43, 4167, 5621, 203, 565, 327, 6736, 510, 6388, 43, 530, 18, 1289, 12, 1484, 17974, 510, 6388, 43, 530, 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 ]
./partial_match/56/0x0dF93c7757B93Fd5C02f516ab18C1BD4A4Bc9a92/sources/A.sol
Deposit fee percent.
uint256 depositFee;
11,218,704
[ 1, 758, 1724, 14036, 5551, 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, 2254, 5034, 443, 1724, 14667, 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 ]
pragma solidity ^0.4.24; /** * @title Transfer Manager module for core transfer validation functionality */ contract GeneralTransferManagerStorage { //Address from which issuances come address public issuanceAddress = address(0); //Address which can sign whitelist changes address public signingAddress = address(0); bytes32 public constant WHITELIST = "WHITELIST"; bytes32 public constant FLAGS = "FLAGS"; //from and to timestamps that an investor can send / receive tokens respectively struct TimeRestriction { //the moment when the sale lockup period ends and the investor can freely sell or transfer away their tokens uint64 canSendAfter; //the moment when the purchase lockup period ends and the investor can freely purchase or receive from others uint64 canReceiveAfter; uint64 expiryTime; uint8 canBuyFromSTO; uint8 added; } // Allows all TimeRestrictions to be offset struct Defaults { uint64 canSendAfter; uint64 canReceiveAfter; } // Offset to be applied to all timings (except KYC expiry) Defaults public defaults; // List of all addresses that have been added to the GTM at some point address[] public investors; // An address can only send / receive tokens once their corresponding uint256 > block.number // (unless allowAllTransfers == true or allowAllWhitelistTransfers == true) mapping (address => TimeRestriction) public whitelist; // Map of used nonces by customer mapping(address => mapping(uint256 => bool)) public nonceMap; //If true, there are no transfer restrictions, for any addresses bool public allowAllTransfers = false; //If true, time lock is ignored for transfers (address must still be on whitelist) bool public allowAllWhitelistTransfers = false; //If true, time lock is ignored for issuances (address must still be on whitelist) bool public allowAllWhitelistIssuances = true; //If true, time lock is ignored for burn transactions bool public allowAllBurnTransfers = false; }
* @title Transfer Manager module for core transfer validation functionality/Address from which issuances comeAddress which can sign whitelist changesfrom and to timestamps that an investor can send / receive tokens respectively
contract GeneralTransferManagerStorage { address public issuanceAddress = address(0); address public signingAddress = address(0); bytes32 public constant WHITELIST = "WHITELIST"; bytes32 public constant FLAGS = "FLAGS"; struct TimeRestriction { uint64 canSendAfter; uint64 canReceiveAfter; uint64 expiryTime; uint8 canBuyFromSTO; uint8 added; } struct Defaults { uint64 canSendAfter; uint64 canReceiveAfter; } Defaults public defaults; address[] public investors; mapping (address => TimeRestriction) public whitelist; mapping(address => mapping(uint256 => bool)) public nonceMap; bool public allowAllTransfers = false; bool public allowAllWhitelistTransfers = false; bool public allowAllWhitelistIssuances = true; bool public allowAllBurnTransfers = false; }
6,428,211
[ 1, 5912, 8558, 1605, 364, 2922, 7412, 3379, 14176, 19, 1887, 628, 1492, 3385, 89, 6872, 12404, 1887, 1492, 848, 1573, 10734, 3478, 2080, 471, 358, 11267, 716, 392, 2198, 395, 280, 848, 1366, 342, 6798, 2430, 19629, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 9544, 5912, 1318, 3245, 288, 203, 203, 565, 1758, 1071, 3385, 89, 1359, 1887, 273, 1758, 12, 20, 1769, 203, 203, 565, 1758, 1071, 10611, 1887, 273, 1758, 12, 20, 1769, 203, 203, 565, 1731, 1578, 1071, 5381, 24353, 7085, 273, 315, 16861, 7085, 14432, 203, 565, 1731, 1578, 1071, 5381, 16993, 273, 315, 17836, 14432, 203, 203, 565, 1958, 2647, 11670, 288, 203, 3639, 2254, 1105, 848, 3826, 4436, 31, 203, 3639, 2254, 1105, 848, 11323, 4436, 31, 203, 3639, 2254, 1105, 10839, 950, 31, 203, 3639, 2254, 28, 848, 38, 9835, 1265, 31487, 31, 203, 3639, 2254, 28, 3096, 31, 203, 565, 289, 203, 203, 565, 1958, 14159, 288, 203, 3639, 2254, 1105, 848, 3826, 4436, 31, 203, 3639, 2254, 1105, 848, 11323, 4436, 31, 203, 565, 289, 203, 203, 203, 203, 203, 203, 565, 14159, 1071, 3467, 31, 203, 565, 1758, 8526, 1071, 2198, 395, 1383, 31, 203, 565, 2874, 261, 2867, 516, 2647, 11670, 13, 1071, 10734, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 11890, 5034, 516, 1426, 3719, 1071, 7448, 863, 31, 203, 565, 1426, 1071, 1699, 1595, 1429, 18881, 273, 629, 31, 203, 565, 1426, 1071, 1699, 1595, 18927, 1429, 18881, 273, 629, 31, 203, 565, 1426, 1071, 1699, 1595, 18927, 7568, 89, 6872, 273, 638, 31, 203, 565, 1426, 1071, 1699, 1595, 38, 321, 1429, 18881, 273, 629, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0x23BECb8A22D3C6978F1A04b891262C832f5Ef3D2/sources/contracts/MasterStar.sol
Withdraw LP tokens from MasterChef. lockup amount
function withdraw(uint256 _pid, uint256 _amount) public nonReentrant { 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.accSpherePerShare).div(1e18).sub( user.rewardDebt ); if (pending > 0) { if (checkLockup()) { uint256 pendingLockup = pending.mul(lockerRate).div(10000); lockupTokens(pendingLockup); pending = pending.sub(pendingLockup); } } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accSpherePerShare).div(1e18); emit Withdraw(msg.sender, _pid, _amount); }
4,535,694
[ 1, 1190, 9446, 511, 52, 2430, 628, 13453, 39, 580, 74, 18, 2176, 416, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 598, 9446, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 1071, 1661, 426, 8230, 970, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 3576, 18, 15330, 15533, 203, 3639, 2583, 12, 1355, 18, 8949, 1545, 389, 8949, 16, 315, 1918, 9446, 30, 486, 7494, 8863, 203, 3639, 1089, 2864, 24899, 6610, 1769, 203, 3639, 2254, 5034, 4634, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 22747, 2173, 9535, 2934, 2892, 12, 21, 73, 2643, 2934, 1717, 12, 203, 5411, 729, 18, 266, 2913, 758, 23602, 203, 3639, 11272, 203, 203, 203, 3639, 309, 261, 9561, 405, 374, 13, 288, 203, 203, 5411, 309, 261, 1893, 2531, 416, 10756, 288, 203, 7734, 2254, 5034, 4634, 2531, 416, 273, 4634, 18, 16411, 12, 739, 264, 4727, 2934, 2892, 12, 23899, 1769, 203, 7734, 2176, 416, 5157, 12, 9561, 2531, 416, 1769, 203, 7734, 4634, 273, 4634, 18, 1717, 12, 9561, 2531, 416, 1769, 203, 5411, 289, 203, 203, 3639, 289, 203, 203, 3639, 309, 261, 67, 8949, 405, 374, 13, 288, 203, 5411, 729, 18, 8949, 273, 729, 18, 8949, 18, 1717, 24899, 8949, 1769, 203, 5411, 2845, 18, 9953, 1345, 18, 4626, 5912, 12, 2867, 12, 3576, 18, 15330, 3631, 389, 8949, 1769, 203, 3639, 289, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 22747, 2173, 9535, 2934, 2892, 12, 21, 2 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./IStablecoin.sol"; abstract contract BlackList is Ownable, ERC20Pausable { /////// Getters to allow the same blacklist to be used also by other contracts (including upgraded Tether) /////// function getBlackListStatus(address _maker) external view returns (bool) { return isBlackListed[_maker]; } function getOwner() external view returns (address) { return owner(); } mapping(address => bool) public isBlackListed; function addBlackList(address _evilUser) public onlyOwner { isBlackListed[_evilUser] = true; emit AddedBlackList(_evilUser); } function removeBlackList(address _clearedUser) public onlyOwner { isBlackListed[_clearedUser] = false; emit RemovedBlackList(_clearedUser); } function destroyBlackFunds(address _blackListedUser) public onlyOwner { require(isBlackListed[_blackListedUser]); uint256 dirtyFunds = balanceOf(_blackListedUser); _burn(_blackListedUser, dirtyFunds); emit DestroyedBlackFunds(_blackListedUser, dirtyFunds); } event DestroyedBlackFunds(address _blackListedUser, uint256 _balance); event AddedBlackList(address _user); event RemovedBlackList(address _user); } /** * @title MeterToken * @dev This contract is template for MTR stablecoins */ contract MeterToken is BlackList, AccessControl, IStablecoin { // Create a new role identifier for the minter role bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) public nonces; /** * @dev Creates an instance of `MeterToken` where `name` and `symbol` is initialized. * Names and symbols can vary from the pegging currency */ constructor( string memory name, string memory symbol, address manager ) ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupRole(MINTER_ROLE, manager); uint256 chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name)), keccak256(bytes("1")), chainId, address(this) ) ); } function setManager(address manager_) public { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "MTRV1: Caller is not a default admin" ); _setupRole(MINTER_ROLE, manager_); } function mint(address to, uint256 amount) external override { // Check that the calling account has the minter role require( hasRole(MINTER_ROLE, msg.sender), "Meter: Caller is not a minter" ); _mint(to, amount); } function pause() external { // Check that the calling account has the pauser role require( hasRole(PAUSER_ROLE, _msgSender()), "Meter: must have pauser role to pause" ); _pause(); } function unpause() external { // Check that the calling account has the pauser role require( hasRole(PAUSER_ROLE, _msgSender()), "Meter: must have pauser role to unpause" ); _unpause(); } function burn(uint256 amount) external override { // Check that the calling account has the burner role require( hasRole(BURNER_ROLE, _msgSender()), "Meter: must have burner role to burn" ); _burn(_msgSender(), amount); } function burnFrom(address account, uint256 amount) external override { uint256 currentAllowance = allowance(account, _msgSender()); require( currentAllowance >= amount, "ERC20: burn amount exceeds allowance" ); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(deadline >= block.timestamp, "UniswapV2: EXPIRED"); 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, "Meter: INVALID_SIGNATURE" ); _approve(owner, spender, value); } }
Check that the calling account has the burner role
function burn(uint256 amount) external override { require( hasRole(BURNER_ROLE, _msgSender()), "Meter: must have burner role to burn" ); _burn(_msgSender(), amount); }
6,489,738
[ 1, 1564, 716, 326, 4440, 2236, 711, 326, 18305, 264, 2478, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18305, 12, 11890, 5034, 3844, 13, 3903, 3849, 288, 203, 3639, 2583, 12, 203, 5411, 28335, 12, 38, 8521, 654, 67, 16256, 16, 389, 3576, 12021, 1435, 3631, 203, 5411, 315, 16935, 30, 1297, 1240, 18305, 264, 2478, 358, 18305, 6, 203, 3639, 11272, 203, 3639, 389, 70, 321, 24899, 3576, 12021, 9334, 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 ]
//Address: 0xB4e4a785de5A9cAEfAD3912A1344fEbF04c7d2aC //Contract name: ArtSale //Balance: 0 Ether //Verification Date: 7/19/2017 //Transacion Count: 23 // CODE STARTS HERE pragma solidity ^0.4.11; /** * Controller */ contract Controller { /// @notice Called when `_owner` sends ether to the token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) returns(bool); } /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } /** * @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 { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public totalSupply; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); event Transfer(address indexed from, address indexed to, uint value); } /** * @title Contracts that should not own Tokens * @dev This blocks incoming ERC23 tokens to prevent accidental loss of tokens. * Should tokens (any ERC20Basic compatible) end up in the contract, it allows the * owner to reclaim the tokens. */ contract HasNoTokens is Ownable { /** * @dev Reject all ERC23 compatible tokens * @param from_ address The address that is transferring the tokens * @param value_ Uint the amount of the specified token * @param data_ Bytes The data passed from the caller. */ function tokenFallback(address from_, uint value_, bytes data_) external { throw; } /** * @dev Reclaim all ERC20Basic compatible tokens * @param tokenAddr address The address of the token contract */ function reclaimToken(address tokenAddr) external onlyOwner { ERC20Basic tokenInst = ERC20Basic(tokenAddr); uint256 balance = tokenInst.balanceOf(this); tokenInst.transfer(owner, balance); } } // @dev Contract to hold ETH raised during a token sale. // Prevents attack in which the Multisig sends raised ether to the // sale contract to mint tokens to itself, and getting the // funds back immediately. contract AbstractSale { function saleFinalized() constant returns (bool); } contract Escrow is HasNoTokens { address public beneficiary; uint public finalBlock; AbstractSale public tokenSale; // @dev Constructor initializes public variables // @param _beneficiary The address of the multisig that will receive the funds // @param _finalBlock Block after which the beneficiary can request the funds function Escrow(address _beneficiary, uint _finalBlock, address _tokenSale) { beneficiary = _beneficiary; finalBlock = _finalBlock; tokenSale = AbstractSale(_tokenSale); } // @dev Receive all sent funds without any further logic function() public payable {} // @dev Withdraw function sends all the funds to the wallet if conditions are correct function withdraw() public { if (msg.sender != beneficiary) throw; if (block.number > finalBlock) return doWithdraw(); if (tokenSale.saleFinalized()) return doWithdraw(); } function doWithdraw() internal { if (!beneficiary.send(this.balance)) throw; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint; mapping (address => uint) balances; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { throw; } _; } /** * @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, uint _value) onlyPayloadSize(2 * 32) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint 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) constant returns (uint); function transferFrom(address from, address to, uint value); function approve(address spender, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /** * @title Standard ERC20 token * * @dev Implemantation of the basic standart 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 BasicToken, ERC20 { mapping (address => mapping (address => uint)) 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 uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); } /** * @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens than 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 uint specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } /** * Controlled */ contract Controlled { address public controller; function Controlled() { controller = msg.sender; } function changeController(address _controller) onlyController { controller = _controller; } modifier onlyController { if (msg.sender != controller) throw; _; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation */ contract MintableToken is StandardToken, Controlled { event Mint(address indexed to, uint value); event MintFinished(); bool public mintingFinished = false; uint public totalSupply = 0; /** * @dev Function to mint tokens * @param _to The address that will recieve 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, uint _amount) onlyController canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyController returns (bool) { mintingFinished = true; MintFinished(); return true; } modifier canMint() { if (mintingFinished) throw; _; } } /** * @title LimitedTransferToken * @dev LimitedTransferToken defines the generic interface and the implementation to limit token * transferability for different events. It is intended to be used as a base class for other token * contracts. * LimitedTransferToken has been designed to allow for different limiting factors, * this can be achieved by recursively calling super.transferableTokens() until the base class is * hit. For example: * function transferableTokens(address holder, uint64 time) constant public returns (uint256) { * return min256(unlockedTokens, super.transferableTokens(holder, time)); * } * A working example is VestedToken.sol: * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/VestedToken.sol */ contract LimitedTransferToken is ERC20 { /** * @dev Checks whether it can transfer or otherwise throws. */ modifier canTransfer(address _sender, uint _value) { if (_value > transferableTokens(_sender, uint64(now))) throw; _; } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _to The address that will recieve the tokens. * @param _value The amount of tokens to be transferred. */ function transfer(address _to, uint _value) canTransfer(msg.sender, _value) { super.transfer(_to, _value); } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _from The address that will send the tokens. * @param _to The address that will recieve the tokens. * @param _value The amount of tokens to be transferred. */ function transferFrom(address _from, address _to, uint _value) canTransfer(_from, _value) { super.transferFrom(_from, _to, _value); } /** * @dev Default transferable tokens function returns all tokens for a holder (no limit). * @dev Overwriting transferableTokens(address holder, uint64 time) is the way to provide the * specific logic for limiting token transferability for a holder over time. */ function transferableTokens(address holder, uint64 time) constant public returns (uint256) { return balanceOf(holder); } } /** * @title Vested token * @dev Tokens that can be vested for a group of addresses. */ contract VestedToken is StandardToken, LimitedTransferToken { uint256 MAX_GRANTS_PER_ADDRESS = 20; struct TokenGrant { address granter; // 20 bytes uint256 value; // 32 bytes uint64 cliff; uint64 vesting; uint64 start; // 3 * 8 = 24 bytes bool revokable; bool burnsOnRevoke; // 2 * 1 = 2 bits? or 2 bytes? } // total 78 bytes = 3 sstore per operation (32 per sstore) mapping (address => TokenGrant[]) public grants; event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint256 grantId); /** * @dev Grant tokens to a specified address * @param _to address The address which the tokens will be granted to. * @param _value uint256 The amount of tokens to be granted. * @param _start uint64 Time of the beginning of the grant. * @param _cliff uint64 Time of the cliff period. * @param _vesting uint64 The vesting period. * @param _revokable bool If the grant is revokable. * @param _burnsOnRevoke bool When true, the tokens are burned if revoked. */ function grantVestedTokens( address _to, uint256 _value, uint64 _start, uint64 _cliff, uint64 _vesting, bool _revokable, bool _burnsOnRevoke ) public { // Check for date inconsistencies that may cause unexpected behavior if (_cliff < _start || _vesting < _cliff) { throw; } if (tokenGrantsCount(_to) > MAX_GRANTS_PER_ADDRESS) throw; // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting). uint count = grants[_to].push( TokenGrant( _revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable _value, _cliff, _vesting, _start, _revokable, _burnsOnRevoke ) ); transfer(_to, _value); NewTokenGrant(msg.sender, _to, _value, count - 1); } /** * @dev Revoke the grant of tokens of a specifed address. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. */ function revokeTokenGrant(address _holder, uint _grantId) public { TokenGrant grant = grants[_holder][_grantId]; if (!grant.revokable) { // Check if grant was revokable throw; } if (grant.granter != msg.sender) { // Only granter can revoke it throw; } address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender; uint256 nonVested = nonVestedTokens(grant, uint64(now)); // remove grant from array delete grants[_holder][_grantId]; grants[_holder][_grantId] = grants[_holder][grants[_holder].length.sub(1)]; grants[_holder].length -= 1; balances[receiver] = balances[receiver].add(nonVested); balances[_holder] = balances[_holder].sub(nonVested); Transfer(_holder, receiver, nonVested); } /** * @dev Calculate the total amount of transferable tokens of a holder at a given time * @param holder address The address of the holder * @param time uint64 The specific time. * @return An uint representing a holder's total amount of transferable tokens. */ function transferableTokens(address holder, uint64 time) constant public returns (uint256) { uint256 grantIndex = tokenGrantsCount(holder); if (grantIndex == 0) return balanceOf(holder); // shortcut for holder without grants // Iterate through all the grants the holder has, and add all non-vested tokens uint256 nonVested = 0; for (uint256 i = 0; i < grantIndex; i++) { nonVested = nonVested.add(nonVestedTokens(grants[holder][i], time)); } // Balance - totalNonVested is the amount of tokens a holder can transfer at any given time uint256 vestedTransferable = balanceOf(holder).sub(nonVested); // Return the minimum of how many vested can transfer and other value // in case there are other limiting transferability factors (default is balanceOf) return SafeMath.min256(vestedTransferable, super.transferableTokens(holder, time)); } /** * @dev Check the amount of grants that an address has. * @param _holder The holder of the grants. * @return A uint representing the total amount of grants. */ function tokenGrantsCount(address _holder) constant returns (uint index) { return grants[_holder].length; } /** * @dev Calculate amount of vested tokens at a specifc time. * @param tokens uint256 The amount of tokens grantted. * @param time uint64 The time to be checked * @param start uint64 A time representing the begining of the grant * @param cliff uint64 The cliff period. * @param vesting uint64 The vesting period. * @return An uint representing the amount of vested tokensof a specif grant. * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . |(grants[_holder] == address(0)) return 0; * | . | * +===+===========+---------+----------> time * Start Clift Vesting */ function calculateVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vesting) constant returns (uint256) { // Shortcuts for before cliff and after vesting cases. if (time < cliff) return 0; if (time >= vesting) return tokens; // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can use just calculate a value // in the vesting rect (as shown in above's figure) // vestedTokens = tokens * (time - start) / (vesting - start) uint256 vestedTokens = tokens.mul(time.sub(start)).div(vesting.sub(start)); return vestedTokens; } /** * @dev Get all information about a specifc grant. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. * @return Returns all the values that represent a TokenGrant(address, value, start, cliff, * revokability, burnsOnRevoke, and vesting) plus the vested value at the current time. */ function tokenGrant(address _holder, uint _grantId) constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) { TokenGrant grant = grants[_holder][_grantId]; granter = grant.granter; value = grant.value; start = grant.start; cliff = grant.cliff; vesting = grant.vesting; revokable = grant.revokable; burnsOnRevoke = grant.burnsOnRevoke; vested = vestedTokens(grant, uint64(now)); } /** * @dev Get the amount of vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time The time to be checked * @return An uint representing the amount of vested tokens of a specific grant at a specific time. */ function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return calculateVestedTokens( grant.value, uint256(time), uint256(grant.start), uint256(grant.cliff), uint256(grant.vesting) ); } /** * @dev Calculate the amount of non vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time uint64 The time to be checked * @return An uint representing the amount of non vested tokens of a specifc grant on the * passed time frame. */ function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return grant.value.sub(vestedTokens(grant, time)); } /** * @dev Calculate the date when the holder can trasfer all its tokens * @param holder address The address of the holder * @return An uint representing the date of the last transferable tokens. */ function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) { date = uint64(now); uint256 grantIndex = grants[holder].length; for (uint256 i = 0; i < grantIndex; i++) { date = SafeMath.max64(grants[holder][i].vesting, date); } } } /// @title Artcoin (ART) - democratizing culture. contract Artcoin is MintableToken, VestedToken { string public constant name = 'Artcoin'; string public constant symbol = 'ART'; uint public constant decimals = 18; function() public payable { if (isContract(controller)) { if (!Controller(controller).proxyPayment.value(msg.value)(msg.sender)) throw; } else { throw; } } function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == address(0)) return false; assembly { size := extcodesize(_addr) } return size > 0; } } /// @title Artcoin Placeholder - democratizing culture. contract ArtcoinPlaceholder is Controller { Artcoin public token; address public tokenSale; function ArtcoinPlaceholder(address _token, address _tokenSale) { token = Artcoin(_token); tokenSale = _tokenSale; } function changeController(address consortium) public { if (msg.sender != tokenSale) throw; token.changeController(consortium); suicide(consortium); } function proxyPayment(address _owner) payable public returns (bool) { throw; return false; } function onTransfer(address _from, address _to, uint _amount) public returns (bool) { return true; } function onApprove(address _owner, address _spender, uint _amount) public returns (bool) { return true; } } /// @title ART Sale - democratizing culture. contract ArtSale is Controller { using SafeMath for uint; address public manager; address public operations; ArtcoinPlaceholder public consortiumPlaceholder; Artcoin public token; Escrow public escrow; uint public initialBlock; // block number in which the sale starts, inclusive. sale will be opened at initial block. uint public finalBlock; // block number in which the sale ends, exclusive, sale will be closed at ends block. uint public initialPrice; // number of wei-Artcoin tokens for 1 wei, at the start of the sale (18 decimals) uint public finalPrice; // number of wei-Artcoin tokens for 1 wei, at the end of the sale uint public priceStages; // number of different price stages for interpolating between initialPrice and finalPrice uint public maximumSubscription; // maximum subscriptions, in wei uint public totalSubscription = 0; // total subscriptions, in wei mapping (address => bool) public activations; // confirmations to activate the sale mapping (address => uint) public subscriptions; // subscriptions uint constant public dust = 1 finney; // minimum investment bool public saleStopped = false; bool public saleFinalized = false; event NewPresaleAllocation(address indexed holder, uint amount); event NewSubscription(address indexed holder, uint amount, uint etherAmount); function ArtSale(address _manager, address _operations, uint _initialBlock, uint _finalBlock, uint256 _initialPrice, uint256 _finalPrice, uint8 _priceStages, uint _maximumSubscription) nonZeroAddress(_operations) { if (_initialBlock < getBlockNumber()) throw; if (_initialBlock >= _finalBlock) throw; if (_initialPrice <= _finalPrice) throw; if (_priceStages < 2) throw; if (_priceStages > _initialPrice - _finalPrice) throw; manager = _manager; operations = _operations; maximumSubscription = _maximumSubscription; initialBlock = _initialBlock; finalBlock = _finalBlock; initialPrice = _initialPrice; finalPrice = _finalPrice; priceStages = _priceStages; } // @notice Set Artcoin token and escrow address. // @param _token: Address of an instance of the Artcoin token // @param _consortiumPlaceholder: Address of the consortium placeholder // @param _escrow: Address of the wallet receiving the funds of the sale function setArtcoin(address _token, address _consortiumPlaceholder, address _escrow) nonZeroAddress(_token) nonZeroAddress(_consortiumPlaceholder) nonZeroAddress(_escrow) public { if (activations[this]) throw; token = Artcoin(_token); consortiumPlaceholder = ArtcoinPlaceholder(_consortiumPlaceholder); escrow = Escrow(_escrow); if (token.controller() != address(this)) throw; // sale is token controller if (token.totalSupply() > 0) throw; // token is empty if (consortiumPlaceholder.tokenSale() != address(this)) throw; // placeholder has reference to sale if (consortiumPlaceholder.token() != address(token)) throw; // placeholder has reference to ART if (escrow.finalBlock() != finalBlock) throw; // final blocks must match if (escrow.beneficiary() != operations) throw; // receiving wallet must match if (escrow.tokenSale() != address(this)) throw; // watched token sale must be self doActivateSale(this); } // @notice Certain addresses need to call the activate function prior to the sale opening block. // This proves that they have checked the sale contract is legit, as well as proving // the capability for those addresses to interact with the contract. function activateSale() public { doActivateSale(msg.sender); } function doActivateSale(address _entity) nonZeroAddress(token) onlyBeforeSale private { activations[_entity] = true; } // @notice Whether the needed accounts have activated the sale. // @return Is sale activated function isActivated() constant public returns (bool) { return activations[this] && activations[operations]; } // @notice Get the price for a Artcoin token at any given block number // @param _blockNumber the block for which the price is requested // @return Number of wei-Artcoin for 1 wei // If sale isn't ongoing for that block, returns 0. function getPrice(uint _blockNumber) constant public returns (uint) { if (_blockNumber < initialBlock || _blockNumber >= finalBlock) return 0; return priceForStage(stageForBlock(_blockNumber)); } // @notice Get what the stage is for a given blockNumber // @param _blockNumber: Block number // @return The sale stage for that block. Stage is between 0 and (priceStages - 1) function stageForBlock(uint _blockNumber) constant internal returns (uint) { uint blockN = _blockNumber.sub(initialBlock); uint totalBlocks = finalBlock.sub(initialBlock); return priceStages.mul(blockN).div(totalBlocks); } // @notice Get what the price is for a given stage // @param _stage: Stage number // @return Price in wei for that stage. // If sale stage doesn't exist, returns 0. function priceForStage(uint _stage) constant internal returns (uint) { if (_stage >= priceStages) return 0; uint priceDifference = initialPrice.sub(finalPrice); uint stageDelta = priceDifference.div(uint(priceStages - 1)); return initialPrice.sub(uint(_stage).mul(stageDelta)); } // @notice Artcoin needs to make initial token allocations for presale partners // This allocation has to be made before the sale is activated. Activating the // sale means no more arbitrary allocations are possible and expresses conformity. // @param _recipient: The receiver of the tokens // @param _amount: Amount of tokens allocated for receiver. function allocatePresaleTokens(address _recipient, uint _amount, uint64 cliffDate, uint64 vestingDate, bool revokable, bool burnOnRevocation) onlyBeforeSaleActivation onlyBeforeSale nonZeroAddress(_recipient) only(operations) public { token.grantVestedTokens(_recipient, _amount, uint64(now), cliffDate, vestingDate, revokable, burnOnRevocation); NewPresaleAllocation(_recipient, _amount); } /// @dev The fallback function is called when ether is sent to the contract, it /// simply calls `doPayment()` with the address that sent the ether as the /// `_subscriber`. Payable is a required solidity modifier for functions to receive /// ether, without this modifier functions will throw if ether is sent to them function() public payable { return doPayment(msg.sender); } /// @dev `doPayment()` is an internal function that sends the ether that this /// contract receives to escrow and creates tokens in the address of the /// @param _subscriber The address that will hold the newly created tokens function doPayment(address _subscriber) onlyDuringSalePeriod onlySaleNotStopped onlySaleActivated nonZeroAddress(_subscriber) minimumValue(dust) internal { if (totalSubscription + msg.value > maximumSubscription) throw; // throw if maximum subscription exceeded uint purchasedTokens = msg.value.mul(getPrice(getBlockNumber())); // number of purchased tokens if (!escrow.send(msg.value)) throw; // escrow funds if (!token.mint(_subscriber, purchasedTokens)) throw; // deliver tokens subscriptions[_subscriber] = subscriptions[_subscriber].add(msg.value); totalSubscription = totalSubscription.add(msg.value); NewSubscription(_subscriber, purchasedTokens, msg.value); } // @notice Function to stop sale before the sale period ends // @dev Only operations is authorized to call this method function stopSale() onlySaleActivated onlySaleNotStopped only(operations) public { saleStopped = true; } // @notice Function to restart stopped sale // @dev Only operations is authorized to call this method function restartSale() onlyDuringSalePeriod onlySaleStopped only(operations) public { saleStopped = false; } // @notice Finalizes sale and distributes Artcoin to purchasers and releases payments // @dev Transfers the token controller power to the consortium. function finalizeSale() onlyAfterSale only(operations) public { doFinalizeSale(); } function doFinalizeSale() internal { uint purchasedTokens = token.totalSupply(); uint advisorTokens = purchasedTokens * 5 / 100; // mint 5% of purchased for advisors if (!token.mint(operations, advisorTokens)) throw; uint managerTokens = purchasedTokens * 25 / 100; // mint 25% of purchased for manager if (!token.mint(manager, managerTokens)) throw; token.changeController(consortiumPlaceholder); saleFinalized = true; saleStopped = true; } // @notice Deploy Artcoin Consortium contract // @param consortium: The address the consortium was deployed at. function deployConsortium(address consortium) onlyFinalizedSale nonZeroAddress(consortium) only(operations) public { consortiumPlaceholder.changeController(consortium); } function setOperations(address _operations) nonZeroAddress(_operations) only(operations) public { operations = _operations; } function getBlockNumber() constant internal returns (uint) { return block.number; } function saleFinalized() constant returns (bool) { return saleFinalized; } function proxyPayment(address _owner) payable public returns (bool) { doPayment(_owner); return true; } /// @notice Notifies the controller about a transfer /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns (bool) { // Until the sale is finalized, only allows transfers originated by the sale contract. // When finalizeSale is called, this function will stop being called and will always be true. return _from == address(this); } /// @notice Notifies the controller about an approval /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns (bool) { return false; } modifier only(address x) { if (msg.sender != x) throw; _; } modifier onlyBeforeSale { if (getBlockNumber() >= initialBlock) throw; _; } modifier onlyDuringSalePeriod { if (getBlockNumber() < initialBlock) throw; if (getBlockNumber() >= finalBlock) throw; _; } modifier onlyAfterSale { if (getBlockNumber() < finalBlock) throw; _; } modifier onlySaleStopped { if (!saleStopped) throw; _; } modifier onlySaleNotStopped { if (saleStopped) throw; _; } modifier onlyBeforeSaleActivation { if (isActivated()) throw; _; } modifier onlySaleActivated { if (!isActivated()) throw; _; } modifier onlyFinalizedSale { if (getBlockNumber() < finalBlock) throw; if (!saleFinalized) throw; _; } modifier nonZeroAddress(address x) { if (x == 0) throw; _; } modifier minimumValue(uint256 x) { if (msg.value < x) throw; _; } }
* @dev Function to mint tokens @param _to The address that will recieve 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, uint _amount) onlyController canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; }
6,463,445
[ 1, 2083, 358, 312, 474, 2430, 225, 389, 869, 1021, 1758, 716, 903, 1950, 21271, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 312, 474, 12, 2867, 389, 869, 16, 2254, 389, 8949, 13, 1338, 2933, 848, 49, 474, 1135, 261, 6430, 13, 288, 203, 565, 2078, 3088, 1283, 273, 2078, 3088, 1283, 18, 1289, 24899, 8949, 1769, 203, 565, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 8949, 1769, 203, 565, 490, 474, 24899, 869, 16, 389, 8949, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; import "@openzeppelin/contracts/utils/Multicall.sol"; import "@openzeppelin/contracts/utils/Base64.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./ACLManager.sol"; import "./TheSpaceRegistry.sol"; import "./ITheSpaceRegistry.sol"; import "./ITheSpace.sol"; contract TheSpace is ITheSpace, Multicall, ReentrancyGuard, ACLManager { TheSpaceRegistry public registry; // token image shared by all tokens string public tokenImageURI = "ipfs://"; constructor( address currencyAddress_, address registryAddress_, string memory tokenImageURI_, address aclManager_, address marketAdmin_, address treasuryAdmin_ ) ACLManager(aclManager_, marketAdmin_, treasuryAdmin_) { // deploy logic contract only and upgrade later if (registryAddress_ != address(0)) { registry = TheSpaceRegistry(registryAddress_); } // deploy logic and registry contracts else { registry = new TheSpaceRegistry( "Planck", // property name "PLK", // property symbol 1000000, // total supply 12, // taxRate 0, // treasuryShare 1 * (10**uint256(ERC20(currencyAddress_).decimals())), // mintTax, 1 $SPACE currencyAddress_ ); } tokenImageURI = tokenImageURI_; } /** * @notice See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId_) external view virtual returns (bool) { return interfaceId_ == type(ITheSpace).interfaceId; } ////////////////////////////// /// Upgradability ////////////////////////////// /// @inheritdoc ITheSpace function upgradeTo(address newImplementation) external onlyRole(Role.aclManager) { registry.transferOwnership(newImplementation); } ////////////////////////////// /// Configuration / Admin ////////////////////////////// function setTotalSupply(uint256 totalSupply_) external onlyRole(Role.marketAdmin) { registry.setTotalSupply(totalSupply_); } /// @inheritdoc ITheSpace function setTaxConfig(ITheSpaceRegistry.ConfigOptions option_, uint256 value_) external onlyRole(Role.marketAdmin) { registry.setTaxConfig(option_, value_); } /// @inheritdoc ITheSpace function withdrawTreasury(address to_) external onlyRole(Role.treasuryAdmin) { (uint256 accumulatedUBI, uint256 accumulatedTreasury, uint256 treasuryWithdrawn) = registry.treasuryRecord(); // calculate available amount and transfer uint256 amount = accumulatedTreasury - treasuryWithdrawn; registry.transferCurrency(to_, amount); registry.emitTreasury(to_, amount); // set `treasuryWithdrawn` to `accumulatedTreasury` registry.setTreasuryRecord(accumulatedUBI, accumulatedTreasury, accumulatedTreasury); } /// @inheritdoc ITheSpace function setTokenImageURI(string memory uri_) external onlyRole(Role.aclManager) { tokenImageURI = uri_; } ////////////////////////////// /// Pixel ////////////////////////////// /// @inheritdoc ITheSpace function getPixel(uint256 tokenId_) external view returns (ITheSpaceRegistry.Pixel memory pixel) { return _getPixel(tokenId_); } function _getPixel(uint256 tokenId_) internal view returns (ITheSpaceRegistry.Pixel memory pixel) { (, uint256 lastTaxCollection, ) = registry.tokenRecord(tokenId_); pixel = ITheSpaceRegistry.Pixel( tokenId_, getPrice(tokenId_), lastTaxCollection, ubiAvailable(tokenId_), getOwner(tokenId_), registry.pixelColor(tokenId_) ); } /// @inheritdoc ITheSpace function setPixel( uint256 tokenId_, uint256 bidPrice_, uint256 newPrice_, uint256 color_ ) external { bid(tokenId_, bidPrice_); setPrice(tokenId_, newPrice_); _setColor(tokenId_, color_, msg.sender); } /// @inheritdoc ITheSpace function setColor(uint256 tokenId_, uint256 color_) public { if (!registry.isApprovedOrOwner(msg.sender, tokenId_)) revert Unauthorized(); _setColor(tokenId_, color_, registry.ownerOf(tokenId_)); } function _setColor( uint256 tokenId_, uint256 color_, address owner_ ) internal { if (registry.pixelColor(tokenId_) == color_) return; registry.setColor(tokenId_, color_, owner_); } /// @inheritdoc ITheSpace function getColor(uint256 tokenId) public view returns (uint256 color) { color = registry.pixelColor(tokenId); } /// @inheritdoc ITheSpace function getPixelsByOwner( address owner_, uint256 limit_, uint256 offset_ ) external view returns ( uint256 total, uint256 limit, uint256 offset, ITheSpaceRegistry.Pixel[] memory pixels ) { uint256 _total = registry.balanceOf(owner_); if (limit_ == 0) { return (_total, limit_, offset_, new ITheSpaceRegistry.Pixel[](0)); } if (offset_ >= _total) { return (_total, limit_, offset_, new ITheSpaceRegistry.Pixel[](0)); } uint256 left = _total - offset_; uint256 size = left > limit_ ? limit_ : left; ITheSpaceRegistry.Pixel[] memory _pixels = new ITheSpaceRegistry.Pixel[](size); for (uint256 i = 0; i < size; i++) { uint256 tokenId = registry.tokenOfOwnerByIndex(owner_, i + offset_); _pixels[i] = _getPixel(tokenId); } return (_total, limit_, offset_, _pixels); } ////////////////////////////// /// Trading ////////////////////////////// /// @inheritdoc ITheSpace function getPrice(uint256 tokenId_) public view returns (uint256 price) { return registry.exists(tokenId_) ? _getPrice(tokenId_) : registry.taxConfig(ITheSpaceRegistry.ConfigOptions.mintTax); } function _getPrice(uint256 tokenId_) internal view returns (uint256) { (uint256 price, , ) = registry.tokenRecord(tokenId_); return price; } /// @inheritdoc ITheSpace function setPrice(uint256 tokenId_, uint256 price_) public { if (!(registry.isApprovedOrOwner(msg.sender, tokenId_))) revert Unauthorized(); if (price_ == _getPrice(tokenId_)) return; bool success = settleTax(tokenId_); if (success) _setPrice(tokenId_, price_); } /** * @dev Internal function to set price without checking */ function _setPrice(uint256 tokenId_, uint256 price_) private { _setPrice(tokenId_, price_, registry.ownerOf(tokenId_)); } function _setPrice( uint256 tokenId_, uint256 price_, address operator_ ) private { // max price to prevent overflow of `_getTax` uint256 maxPrice = registry.currency().totalSupply(); if (price_ > maxPrice) revert PriceTooHigh(maxPrice); (, , uint256 ubiWithdrawn) = registry.tokenRecord(tokenId_); registry.setTokenRecord(tokenId_, price_, block.number, ubiWithdrawn); registry.emitPrice(tokenId_, price_, operator_); } /// @inheritdoc ITheSpace function getOwner(uint256 tokenId_) public view returns (address owner) { return registry.exists(tokenId_) ? registry.ownerOf(tokenId_) : address(0); } /// @inheritdoc ITheSpace function bid(uint256 tokenId_, uint256 price_) public nonReentrant { address owner = getOwner(tokenId_); uint256 askPrice = _getPrice(tokenId_); uint256 mintTax = registry.taxConfig(ITheSpaceRegistry.ConfigOptions.mintTax); // bid price and payee is calculated based on tax and token status uint256 bidPrice; if (registry.exists(tokenId_)) { // skip if already own if (owner == msg.sender) return; // clear tax bool success = _collectTax(tokenId_); // proceed with transfer if (success) { // if tax fully paid, owner get paid normally bidPrice = askPrice; // revert if price too low if (price_ < bidPrice) revert PriceTooLow(); // settle ERC20 token registry.transferCurrencyFrom(msg.sender, owner, bidPrice); // settle ERC721 token registry.safeTransferByMarket(owner, msg.sender, tokenId_); // emit deal event registry.emitDeal(tokenId_, owner, msg.sender, bidPrice); return; } else { // if tax not fully paid, token is treated as defaulted and mint tax is collected and recorded registry.burn(tokenId_); } } // mint tax is collected and recorded bidPrice = mintTax; // revert if price too low if (price_ < bidPrice) revert PriceTooLow(); // settle ERC20 token registry.transferCurrencyFrom(msg.sender, address(registry), bidPrice); // record as tax income _recordTax(tokenId_, msg.sender, mintTax); // settle ERC721 token registry.mint(msg.sender, tokenId_); // emit deal event registry.emitDeal(tokenId_, address(0), msg.sender, bidPrice); } ////////////////////////////// /// Tax & UBI ////////////////////////////// /// @inheritdoc ITheSpace function getTax(uint256 tokenId_) public view returns (uint256) { if (!registry.exists(tokenId_)) revert TokenNotExists(); return _getTax(tokenId_); } function _getTax(uint256 tokenId_) internal view returns (uint256) { (uint256 price, uint256 lastTaxCollection, ) = registry.tokenRecord(tokenId_); if (price == 0) return 0; uint256 taxRate = registry.taxConfig(ITheSpaceRegistry.ConfigOptions.taxRate); // `1000` for every `1000` blocks, `10000` for conversion from bps return ((price * taxRate * (block.number - lastTaxCollection)) / (1000 * 10000)); } /// @inheritdoc ITheSpace function evaluateOwnership(uint256 tokenId_) public view returns (uint256 collectable, bool shouldDefault) { uint256 tax = getTax(tokenId_); if (tax > 0) { // calculate collectable amount address taxpayer = registry.ownerOf(tokenId_); uint256 allowance = registry.currency().allowance(taxpayer, address(registry)); uint256 balance = registry.currency().balanceOf(taxpayer); uint256 available = allowance < balance ? allowance : balance; if (available >= tax) { // can pay tax fully and do not need to be defaulted return (tax, false); } else { // cannot pay tax fully and need to be defaulted return (available, true); } } else { // not tax needed return (0, false); } } /** * @notice Collect outstanding tax for a given token, put token on tax sale if obligation not met. * @dev Emits a {Tax} event * @dev Emits a {Price} event (when properties are put on tax sale). */ function _collectTax(uint256 tokenId_) private returns (bool success) { (uint256 collectable, bool shouldDefault) = evaluateOwnership(tokenId_); if (collectable > 0) { // collect and record tax address owner = registry.ownerOf(tokenId_); registry.transferCurrencyFrom(owner, address(registry), collectable); _recordTax(tokenId_, owner, collectable); } return !shouldDefault; } /** * @notice Update tax record and emit Tax event. */ function _recordTax( uint256 tokenId_, address taxpayer_, uint256 amount_ ) private { // calculate treasury change uint256 treasuryShare = registry.taxConfig(ITheSpaceRegistry.ConfigOptions.treasuryShare); uint256 treasuryAdded = (amount_ * treasuryShare) / 10000; // set treasury record (uint256 accumulatedUBI, uint256 accumulatedTreasury, uint256 treasuryWithdrawn) = registry.treasuryRecord(); registry.setTreasuryRecord( accumulatedUBI + (amount_ - treasuryAdded), accumulatedTreasury + treasuryAdded, treasuryWithdrawn ); // update lastTaxCollection and emit tax event (uint256 price, , uint256 ubiWithdrawn) = registry.tokenRecord(tokenId_); registry.setTokenRecord(tokenId_, price, block.number, ubiWithdrawn); registry.emitTax(tokenId_, taxpayer_, amount_); } /// @inheritdoc ITheSpace function settleTax(uint256 tokenId_) public returns (bool success) { success = _collectTax(tokenId_); if (!success) registry.burn(tokenId_); } /// @inheritdoc ITheSpace function ubiAvailable(uint256 tokenId_) public view returns (uint256) { (uint256 accumulatedUBI, , ) = registry.treasuryRecord(); (, , uint256 ubiWithdrawn) = registry.tokenRecord(tokenId_); return accumulatedUBI / registry.totalSupply() - ubiWithdrawn; } /// @inheritdoc ITheSpace function withdrawUbi(uint256 tokenId_) external { uint256 amount = ubiAvailable(tokenId_); if (amount > 0) { // transfer address recipient = registry.ownerOf(tokenId_); registry.transferCurrency(recipient, amount); // record (uint256 price, uint256 lastTaxCollection, uint256 ubiWithdrawn) = registry.tokenRecord(tokenId_); registry.setTokenRecord(tokenId_, price, lastTaxCollection, ubiWithdrawn + amount); // emit event registry.emitUBI(tokenId_, recipient, amount); } } ////////////////////////////// /// Registry backcall ////////////////////////////// /// @inheritdoc ITheSpace function _beforeTransferByRegistry(uint256 tokenId_) external returns (bool success) { if (msg.sender != address(registry)) revert Unauthorized(); // clear tax or default settleTax(tokenId_); // proceed with transfer if tax settled if (registry.exists(tokenId_)) { // transfer is regarded as setting price to 0, then bid for free // this is to prevent transferring huge tax obligation as a form of attack _setPrice(tokenId_, 0); success = true; } else { success = false; } } /// @inheritdoc ITheSpace function _tokenURI(uint256 tokenId_) external view returns (string memory uri) { if (msg.sender != address(registry)) revert Unauthorized(); if (!registry.exists(tokenId_)) revert TokenNotExists(); string memory tokenName = string(abi.encodePacked("Planck #", Strings.toString(tokenId_))); string memory description = "One of 1 million pixels traded under Harberger Tax and UBI."; string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name": "', tokenName, '", "description": "', description, '", "attributes": [', '], "image": "', tokenImageURI, '"}' ) ) ) ); uri = string(abi.encodePacked("data:application/json;base64,", json)); } }
* @notice Collect outstanding tax for a given token, put token on tax sale if obligation not met. @dev Emits a {Tax} event @dev Emits a {Price} event (when properties are put on tax sale)./ collect and record tax
function _collectTax(uint256 tokenId_) private returns (bool success) { (uint256 collectable, bool shouldDefault) = evaluateOwnership(tokenId_); if (collectable > 0) { address owner = registry.ownerOf(tokenId_); registry.transferCurrencyFrom(owner, address(registry), collectable); _recordTax(tokenId_, owner, collectable); } return !shouldDefault; }
5,503,691
[ 1, 10808, 20974, 5320, 364, 279, 864, 1147, 16, 1378, 1147, 603, 5320, 272, 5349, 309, 320, 31627, 367, 486, 5100, 18, 225, 7377, 1282, 279, 288, 7731, 97, 871, 225, 7377, 1282, 279, 288, 5147, 97, 871, 261, 13723, 1790, 854, 1378, 603, 5320, 272, 5349, 2934, 19, 3274, 471, 1409, 5320, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 14676, 7731, 12, 11890, 5034, 1147, 548, 67, 13, 3238, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 261, 11890, 5034, 3274, 429, 16, 1426, 1410, 1868, 13, 273, 5956, 5460, 12565, 12, 2316, 548, 67, 1769, 203, 203, 3639, 309, 261, 14676, 429, 405, 374, 13, 288, 203, 5411, 1758, 3410, 273, 4023, 18, 8443, 951, 12, 2316, 548, 67, 1769, 203, 5411, 4023, 18, 13866, 7623, 1265, 12, 8443, 16, 1758, 12, 9893, 3631, 3274, 429, 1769, 203, 5411, 389, 3366, 7731, 12, 2316, 548, 67, 16, 3410, 16, 3274, 429, 1769, 203, 3639, 289, 203, 203, 3639, 327, 401, 13139, 1868, 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 ]
./partial_match/1/0xb3B7D98153272E0B5FFe7022B3B43571e4605edb/sources/StabilizeStrategySGRArbV3.sol
20000 = 20% of WETH goes to executor
uint256 public percentExecutor = 20000;
2,822,036
[ 1, 22, 2787, 273, 4200, 9, 434, 678, 1584, 44, 13998, 358, 6601, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 5551, 6325, 273, 576, 2787, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x610142Acd45672894bE44fB9C14376101Ec4Dc16/sources/contracts/ssp/dusty.sol
nonReEntrant by calling console.log(block.timestamp);
function dustMainSale( address buyer, uint256 dustAmount, uint256 number_to_buy ) internal { require(checkSaleIsActive(), "Sale is not active"); require( dustAmount == fullDustPrice * number_to_buy, "incorrect amount of dust supplied" ); require(number_to_buy < maxPerSaleMint, "too many tokens requested"); _mintCards(number_to_buy, buyer); _split777(dustAmount); emit DustSale(buyer, number_to_buy, dustAmount); }
8,416,240
[ 1, 5836, 426, 664, 313, 970, 635, 4440, 2983, 18, 1330, 12, 2629, 18, 5508, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 302, 641, 6376, 30746, 12, 203, 3639, 1758, 27037, 16, 203, 3639, 2254, 5034, 302, 641, 6275, 16, 203, 3639, 2254, 5034, 1300, 67, 869, 67, 70, 9835, 203, 565, 262, 2713, 288, 203, 3639, 2583, 12, 1893, 30746, 2520, 3896, 9334, 315, 30746, 353, 486, 2695, 8863, 203, 3639, 2583, 12, 203, 5411, 302, 641, 6275, 422, 1983, 40, 641, 5147, 380, 1300, 67, 869, 67, 70, 9835, 16, 203, 5411, 315, 267, 6746, 3844, 434, 302, 641, 4580, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 2696, 67, 869, 67, 70, 9835, 411, 943, 2173, 30746, 49, 474, 16, 315, 16431, 4906, 2430, 3764, 8863, 203, 3639, 389, 81, 474, 30492, 12, 2696, 67, 869, 67, 70, 9835, 16, 27037, 1769, 203, 3639, 389, 4939, 14509, 12, 72, 641, 6275, 1769, 203, 3639, 3626, 463, 641, 30746, 12, 70, 16213, 16, 1300, 67, 869, 67, 70, 9835, 16, 302, 641, 6275, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xc773343AdB95E3888D754C927e0eaaA20589F3b4/sources/contracts/BDERC1155Tradable.sol
* @dev Creates a new token type and assigns _initialSupply to an address NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs) @param _initialOwner address of the first owner of the token @param _initialSupply amount to supply the first owner @param _uri Optional URI for this token type @param _data Data to pass if receiver is contract @return The newly created token ID/
function create( address _initialOwner, uint256 _initialSupply, string calldata _uri, bytes calldata _data ) external onlyOwner returns (uint256) { uint256 _id = _getNextTokenID(); _incrementTokenTypeId(); creators[_id] = msg.sender; if (bytes(_uri).length > 0) { emit URI(_uri, _id); } _mint(_initialOwner, _id, _initialSupply, _data); tokenSupply[_id] = _initialSupply; return _id; }
3,651,568
[ 1, 2729, 279, 394, 1147, 618, 471, 22698, 389, 6769, 3088, 1283, 358, 392, 1758, 5219, 30, 1206, 1338, 5541, 309, 1846, 2545, 12126, 1087, 606, 358, 752, 394, 2430, 603, 3433, 6835, 261, 12784, 2026, 2549, 3433, 7115, 13, 225, 389, 6769, 5541, 1758, 434, 326, 1122, 3410, 434, 326, 1147, 225, 389, 6769, 3088, 1283, 3844, 358, 14467, 326, 1122, 3410, 225, 389, 1650, 4055, 3699, 364, 333, 1147, 618, 225, 389, 892, 1910, 358, 1342, 309, 5971, 353, 6835, 327, 1021, 10894, 2522, 1147, 1599, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 752, 12, 203, 3639, 1758, 389, 6769, 5541, 16, 203, 3639, 2254, 5034, 389, 6769, 3088, 1283, 16, 203, 3639, 533, 745, 892, 389, 1650, 16, 203, 3639, 1731, 745, 892, 389, 892, 203, 565, 262, 3903, 1338, 5541, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 389, 350, 273, 389, 588, 9399, 734, 5621, 203, 3639, 389, 15016, 1345, 11731, 5621, 203, 3639, 1519, 3062, 63, 67, 350, 65, 273, 1234, 18, 15330, 31, 203, 203, 3639, 309, 261, 3890, 24899, 1650, 2934, 2469, 405, 374, 13, 288, 203, 5411, 3626, 3699, 24899, 1650, 16, 389, 350, 1769, 203, 3639, 289, 203, 203, 3639, 389, 81, 474, 24899, 6769, 5541, 16, 389, 350, 16, 389, 6769, 3088, 1283, 16, 389, 892, 1769, 203, 3639, 1147, 3088, 1283, 63, 67, 350, 65, 273, 389, 6769, 3088, 1283, 31, 203, 3639, 327, 389, 350, 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 ]
./full_match/4/0xcF9C5EA1373f233F323156C2249662Cf9c60386d/sources/contracts/AbstractToken.sol
* Create new Abstract Token contract./ Do nothing
constructor () { }
755,033
[ 1, 1684, 394, 4115, 3155, 6835, 18, 19, 2256, 5083, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 3885, 1832, 288, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* * ETHEREUM ACCUMULATIVE SMARTCONTRACT * Web - https://highfiveeth.org * Twitter - https://twitter.com/highfiveeth * Telegram_channel - https://t.me/highfiveeth * EN Telegram_chat: https://t.me/highfiveeth_en * RU Telegram_chat: https://t.me/highfiveeth_ru * CN Telegram_chat: https://t.me/highfiveeth_cn * * - GAIN 4-5% OF YOUR DEPOSIT PER 24 HOURS (every 5900 blocks) * - 4% IF YOUR TOTAL DEPOSIT 0.01-1 ETH * - 4.25% IF YOUR TOTAL DEPOSIT 1-10 ETH * - 4.5% IF YOUR TOTAL DEPOSIT 10-20 ETH * - 4.75% IF YOUR TOTAL DEPOSIT 20-40 ETH * - 5% IF YOUR TOTAL DEPOSIT 40+ ETH * - Life-long payments * - The revolutionary reliability * - Minimal contribution is 0.01 eth * - Currency and payment - ETH * - !!!It is not allowed to transfer from exchanges, only from your personal ETH wallet!!! * - Contribution allocation schemes: * -- 88% payments * -- 12% Marketing + Operating Expenses * * ---About the Project * Blockchain-enabled smart contracts have opened a new era of trustless relationships without * intermediaries. This technology opens incredible financial possibilities. Our automated investment * distribution model is written into a smart contract, uploaded to the Ethereum blockchain and can be * freely accessed online. In order to insure our investors&#39; complete security, full control over the * project has been transferred from the organizers to the smart contract: nobody can influence the * system&#39;s permanent autonomous functioning. * * ---How to use: * 1. Send from ETH wallet to the smart contract address "0x7c2d76735b09de69c1ead5849b3a5176fa688f4a" * any amount above 0.01 ETH. * 2. Verify your transaction in the history of your application or etherscan.io, specifying the address * of your wallet. * 3a. Claim your profit by sending 0 ether transaction * OR * 3b. For reinvest, you need first to remove the accumulated percentage of charges (by sending 0 ether * transaction), and only after that, deposit the amount that you want to reinvest. * * RECOMMENDED GAS LIMIT: 200000 * RECOMMENDED GAS PRICE: https://ethgasstation.info/ * You can check the payments on the etherscan.io site, in the "Internal Txns" tab of your wallet. * * * Contracts reviewed and approved by pros! */ pragma solidity ^0.4.25; contract Highfiveeth { mapping (address => uint256) invested; mapping (address => uint256) atBlock; uint256 minValue; address owner1; // 10% address owner2; // 1% address owner3; // 1% event Withdraw (address indexed _to, uint256 _amount); event Invested (address indexed _to, uint256 _amount); constructor () public { owner1 = 0xA20AFFf23F2F069b7DE37D8bbf9E5ce0BA97989C; // 10% owner2 = 0x9712dF59b31226C48F1c405E7C7e36c0D1c00031; // 1% owner3 = 0xC0a411924b146c19e8E07c180aeE4cC945Cc28a2; // 1% minValue = 0.01 ether; //min amount for transaction } /** * This function calculated percent * less than 1 Ether - 4.0 % * 1-10 Ether - 4.25 % * 10-20 Ether - 4.5 % * 20-40 Ether - 4.75 % * more than 40 Ether - 5.0 % */ function getPercent(address _investor) internal view returns (uint256) { uint256 percent = 400; if(invested[_investor] >= 1 ether && invested[_investor] < 10 ether) { percent = 425; } if(invested[_investor] >= 10 ether && invested[_investor] < 20 ether) { percent = 450; } if(invested[_investor] >= 20 ether && invested[_investor] < 40 ether) { percent = 475; } if(invested[_investor] >= 40 ether) { percent = 500; } return percent; } /** * Main function */ function () external payable { require (msg.value == 0 || msg.value >= minValue,"Min Amount for investing is 0.01 Ether."); uint256 invest = msg.value; address sender = msg.sender; //fee owners owner1.transfer(invest / 10); owner2.transfer(invest / 100); owner3.transfer(invest / 100); if (invested[sender] != 0) { uint256 amount = invested[sender] * getPercent(sender) / 10000 * (block.number - atBlock[sender]) / 5900; //fee sender sender.transfer(amount); emit Withdraw (sender, amount); } atBlock[sender] = block.number; invested[sender] += invest; if (invest > 0){ emit Invested(sender, invest); } } /** * This function show deposit */ function showDeposit (address _deposit) public view returns(uint256) { return invested[_deposit]; } /** * This function show block of last change */ function showLastChange (address _deposit) public view returns(uint256) { return atBlock[_deposit]; } /** * This function show unpayed percent of deposit */ function showUnpayedPercent (address _deposit) public view returns(uint256) { uint256 amount = invested[_deposit] * getPercent(_deposit) / 10000 * (block.number - atBlock[_deposit]) / 5900; return amount; } }
* This function show deposit/
function showDeposit (address _deposit) public view returns(uint256) { return invested[_deposit]; }
6,743,975
[ 1, 2503, 445, 2405, 443, 1724, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2405, 758, 1724, 261, 2867, 389, 323, 1724, 13, 1071, 1476, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 327, 2198, 3149, 63, 67, 323, 1724, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xBbc13396b429b34fD1300652DcF75B6A0d3D4853/sources/Sponsio.sol
Make prediction for Event. Pay in SIO, rewards in MRCS Check if we need to End event because time ended Trying to pay royalties
function makePrediction(uint32 eventId, bytes32 predictionString) public EventExists(eventId) returns (bool) { Event storage eventum = allEvents[eventId]; require(eventum.eventStatus == EventStatus.Active, "Event invalid"); if (eventum.timeSettings.endTime > 0 && uint32(block.timestamp) > eventum.timeSettings.endTime){ eventum.timeSettings.lastActiveTime = eventum.timeSettings.endTime; eventum.eventStatus = EventStatus.OutOfTime; return false; } require(balanceOf(msg.sender) >= eventum.predictionPrice, "Insufficient payment amount"); uint256 finalPredictCost; if (eventum.royaltySetting.royaltyOnlyLosers == 0){ uint256 predictionPriceDiv100 = eventum.predictionPrice.div(100); require(transfer(eventum.creator, predictionPriceDiv100.mul(eventum.royaltySetting.royaltyForCreator)), "Failed to pay"); require(transfer(owner(), predictionPriceDiv100.mul(eventum.royaltySetting.royaltyForContract)), "Failed to pay"); finalPredictCost = predictionPriceDiv100.mul(100 - eventum.royaltySetting.royaltyForContract - eventum.royaltySetting.royaltyForCreator); } else{ finalPredictCost = eventum.predictionPrice; } Prediction memory prediction; prediction.predictionAddress = msg.sender; prediction.timestamp = uint32(block.timestamp); predictions[eventId][predictionString].push(prediction); predictionsByAddressCounts[eventId][msg.sender] += 1; eventum.prize = eventum.prize.add(finalPredictCost); totalWinAllTime = totalWinAllTime.add(finalPredictCost); contractMercesInstance.getRewardFromSponsio(msg.sender); return true; }
11,003,015
[ 1, 6464, 8239, 364, 2587, 18, 13838, 316, 348, 4294, 16, 283, 6397, 316, 490, 54, 4596, 2073, 309, 732, 1608, 358, 4403, 871, 2724, 813, 16926, 6161, 310, 358, 8843, 721, 93, 2390, 606, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1221, 20766, 12, 11890, 1578, 26004, 16, 1731, 1578, 8239, 780, 13, 1071, 2587, 4002, 12, 2575, 548, 13, 1135, 261, 6430, 13, 288, 203, 3639, 2587, 2502, 871, 379, 273, 777, 3783, 63, 2575, 548, 15533, 203, 3639, 2583, 12, 2575, 379, 18, 2575, 1482, 422, 2587, 1482, 18, 3896, 16, 315, 1133, 2057, 8863, 203, 3639, 309, 261, 2575, 379, 18, 957, 2628, 18, 409, 950, 405, 374, 597, 2254, 1578, 12, 2629, 18, 5508, 13, 405, 871, 379, 18, 957, 2628, 18, 409, 950, 15329, 203, 5411, 871, 379, 18, 957, 2628, 18, 2722, 3896, 950, 273, 871, 379, 18, 957, 2628, 18, 409, 950, 31, 203, 5411, 871, 379, 18, 2575, 1482, 273, 2587, 1482, 18, 11224, 950, 31, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 3639, 2583, 12, 12296, 951, 12, 3576, 18, 15330, 13, 1545, 871, 379, 18, 15803, 5147, 16, 315, 5048, 11339, 5184, 3844, 8863, 203, 3639, 2254, 5034, 727, 21362, 8018, 31, 203, 3639, 309, 261, 2575, 379, 18, 3800, 15006, 5568, 18, 3800, 15006, 3386, 48, 538, 414, 422, 374, 15329, 203, 5411, 2254, 5034, 8239, 5147, 7244, 6625, 273, 871, 379, 18, 15803, 5147, 18, 2892, 12, 6625, 1769, 203, 5411, 2583, 12, 13866, 12, 2575, 379, 18, 20394, 16, 8239, 5147, 7244, 6625, 18, 16411, 12, 2575, 379, 18, 3800, 15006, 5568, 18, 3800, 15006, 1290, 10636, 13, 3631, 315, 2925, 358, 8843, 8863, 203, 5411, 2583, 12, 13866, 12, 8443, 9334, 8239, 5147, 7244, 6625, 18, 16411, 2 ]
/** *Submitted for verification at Etherscan.io on 2020-07-24 */ // Copyright (C) 2020 Maker Ecosystem Growth Holdings, INC. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity 0.5.12; // https://github.com/dapphub/ds-pause contract DSPauseAbstract { function setOwner(address) public; function setAuthority(address) public; function setDelay(uint256) public; function plans(bytes32) public view returns (bool); function proxy() public view returns (address); function delay() public view returns (uint256); function plot(address, bytes32, bytes memory, uint256) public; function drop(address, bytes32, bytes memory, uint256) public; function exec(address, bytes32, bytes memory, uint256) public returns (bytes memory); } // https://github.com/makerdao/dss/blob/master/src/jug.sol contract JugAbstract { function wards(address) public view returns (uint256); function rely(address) external; function deny(address) external; function ilks(bytes32) public view returns (uint256, uint256); function vat() public view returns (address); function vow() public view returns (address); function base() public view returns (address); function init(bytes32) external; function file(bytes32, bytes32, uint256) external; function file(bytes32, uint256) external; function file(bytes32, address) external; function drip(bytes32) external returns (uint256); } // https://github.com/makerdao/dss/blob/master/src/pot.sol contract PotAbstract { function wards(address) public view returns (uint256); function rely(address) external; function deny(address) external; function pie(address) public view returns (uint256); function Pie() public view returns (uint256); function dsr() public view returns (uint256); function chi() public view returns (uint256); function vat() public view returns (address); function vow() public view returns (address); function rho() public view returns (uint256); function live() public view returns (uint256); function file(bytes32, uint256) external; function file(bytes32, address) external; function cage() external; function drip() external returns (uint256); function join(uint256) external; function exit(uint256) external; } // https://github.com/makerdao/dss/blob/master/src/spot.sol contract SpotAbstract { function wards(address) public view returns (uint256); function rely(address) external; function deny(address) external; function ilks(bytes32) public view returns (address, uint256); function vat() public view returns (address); function par() public view returns (uint256); function live() public view returns (uint256); function file(bytes32, bytes32, address) external; function file(bytes32, uint256) external; function file(bytes32, bytes32, uint256) external; function poke(bytes32) external; function cage() external; } // https://github.com/makerdao/median contract MedianAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function age() external view returns (uint32); function wat() external view returns (bytes32); function bar() external view returns (uint256); function orcl(address) external view returns (uint256); function bud(address) external view returns (uint256); function slot(uint8) external view returns (address); function read() external view returns (uint256); function peek() external view returns (uint256, bool); function lift(address[] calldata) external; function drop(address[] calldata) external; function setBar(uint256) external; function kiss(address) external; function diss(address) external; function kiss(address[] calldata) external; function diss(address[] calldata) external; function poke(uint256[] calldata, uint256[] calldata, uint8[] calldata, bytes32[] calldata, bytes32[] calldata) external; } contract SpellAction { // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions string constant public description = "2020-07-24 MakerDAO Executive Spell"; // The contracts in this list should correspond to MCD core contracts, verify // against the current release list at: // https://changelog.makerdao.com/releases/mainnet/1.0.8/contracts.json address constant MCD_JUG = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address constant MCD_POT = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; address constant MCD_SPOT = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address constant GITCOIN_OLD = 0xA4188B523EccECFbAC49855eB52eA0b55c4d56dd; address constant GITCOIN = 0x77EB6CF8d732fe4D92c427fCdd83142DB3B742f7; address constant BATUSD = 0x18B4633D6E39870f398597f3c1bA8c4A41294966; address constant BTCUSD = 0xe0F30cb149fAADC7247E953746Be9BbBB6B5751f; address constant ETHBTC = 0x81A679f98b63B3dDf2F17CB5619f4d6775b3c5ED; address constant ETHUSD = 0x64DE91F5A373Cd4c28de3600cB34C7C6cE410C85; address constant KNCUSD = 0x83076a2F42dc1925537165045c9FDe9A4B71AD97; address constant ZRXUSD = 0x956ecD6a9A9A0d84e8eB4e6BaaC09329E202E55e; uint256 constant THOUSAND = 10**3; uint256 constant MILLION = 10**6; uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; uint256 constant RAD = 10**45; // Many of the settings that change weekly rely on the rate accumulator // described at https://docs.makerdao.com/smart-contract-modules/rates-module // To check this yourself, use the following rate calculation (example 8%): // // $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )' function execute() external { // Perform drips PotAbstract(MCD_POT).drip(); JugAbstract(MCD_JUG).drip("ETH-A"); JugAbstract(MCD_JUG).drip("BAT-A"); JugAbstract(MCD_JUG).drip("USDC-A"); JugAbstract(MCD_JUG).drip("USDC-B"); JugAbstract(MCD_JUG).drip("TUSD-A"); JugAbstract(MCD_JUG).drip("WBTC-A"); JugAbstract(MCD_JUG).drip("KNC-A"); JugAbstract(MCD_JUG).drip("ZRX-A"); address[] memory gitcoin_old = new address[](1); gitcoin_old[0] = GITCOIN_OLD; address[] memory gitcoin = new address[](1); gitcoin[0] = GITCOIN; // Drop Old Gitcoin MedianAbstract(BATUSD).drop(gitcoin_old); MedianAbstract(BTCUSD).drop(gitcoin_old); MedianAbstract(ETHBTC).drop(gitcoin_old); MedianAbstract(ETHUSD).drop(gitcoin_old); MedianAbstract(KNCUSD).drop(gitcoin_old); MedianAbstract(ZRXUSD).drop(gitcoin_old); // Lift New Gitcoin MedianAbstract(BATUSD).lift(gitcoin); MedianAbstract(BTCUSD).lift(gitcoin); MedianAbstract(ETHBTC).lift(gitcoin); MedianAbstract(ETHUSD).lift(gitcoin); MedianAbstract(KNCUSD).lift(gitcoin); MedianAbstract(ZRXUSD).lift(gitcoin); // Set the USDC-A Liquidation Ratio // Existing mat: 120% // New mat: 110% SpotAbstract(MCD_SPOT).file("USDC-A", "mat", 110 * RAY / 100); // Update USDC-A spot value in Vat SpotAbstract(MCD_SPOT).poke("USDC-A"); } } contract DssSpell { DSPauseAbstract public pause = DSPauseAbstract(0xbE286431454714F511008713973d3B053A2d38f3); address public action; bytes32 public tag; uint256 public eta; bytes public sig; uint256 public expiration; bool public done; constructor() public { sig = abi.encodeWithSignature("execute()"); action = address(new SpellAction()); bytes32 _tag; address _action = action; assembly { _tag := extcodehash(_action) } tag = _tag; expiration = now + 30 days; } function description() public view returns (string memory) { return SpellAction(action).description(); } function schedule() public { require(now <= expiration, "This contract has expired"); require(address(this).balance == 0, "This spell has already been scheduled"); //inject PRESENT ETHER eta = now + DSPauseAbstract(pause).delay(); pause.plot(action, tag, sig, eta); } function cast() public { require(!done, "spell-already-cast"); done = true; pause.exec(action, tag, sig, eta); } }
Perform drips Drop Old Gitcoin Lift New Gitcoin Set the USDC-A Liquidation Ratio Existing mat: 120% New mat: 110% Update USDC-A spot value in Vat
function execute() external { PotAbstract(MCD_POT).drip(); JugAbstract(MCD_JUG).drip("ETH-A"); JugAbstract(MCD_JUG).drip("BAT-A"); JugAbstract(MCD_JUG).drip("USDC-A"); JugAbstract(MCD_JUG).drip("USDC-B"); JugAbstract(MCD_JUG).drip("TUSD-A"); JugAbstract(MCD_JUG).drip("WBTC-A"); JugAbstract(MCD_JUG).drip("KNC-A"); JugAbstract(MCD_JUG).drip("ZRX-A"); address[] memory gitcoin_old = new address[](1); gitcoin_old[0] = GITCOIN_OLD; address[] memory gitcoin = new address[](1); gitcoin[0] = GITCOIN; MedianAbstract(BATUSD).drop(gitcoin_old); MedianAbstract(BTCUSD).drop(gitcoin_old); MedianAbstract(ETHBTC).drop(gitcoin_old); MedianAbstract(ETHUSD).drop(gitcoin_old); MedianAbstract(KNCUSD).drop(gitcoin_old); MedianAbstract(ZRXUSD).drop(gitcoin_old); MedianAbstract(BATUSD).lift(gitcoin); MedianAbstract(BTCUSD).lift(gitcoin); MedianAbstract(ETHBTC).lift(gitcoin); MedianAbstract(ETHUSD).lift(gitcoin); MedianAbstract(KNCUSD).lift(gitcoin); MedianAbstract(ZRXUSD).lift(gitcoin); SpotAbstract(MCD_SPOT).file("USDC-A", "mat", 110 * RAY / 100); SpotAbstract(MCD_SPOT).poke("USDC-A"); }
7,240,774
[ 1, 4990, 302, 566, 1121, 10895, 18613, 6646, 12645, 511, 2136, 1166, 6646, 12645, 1000, 326, 11836, 5528, 17, 37, 511, 18988, 350, 367, 534, 4197, 28257, 4834, 30, 15743, 9, 1166, 4834, 30, 20168, 9, 2315, 11836, 5528, 17, 37, 16463, 460, 316, 25299, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1836, 1435, 3903, 288, 203, 3639, 23435, 7469, 12, 49, 10160, 67, 52, 1974, 2934, 72, 21335, 5621, 203, 203, 3639, 804, 637, 7469, 12, 49, 10160, 67, 46, 57, 43, 2934, 72, 21335, 2932, 1584, 44, 17, 37, 8863, 203, 3639, 804, 637, 7469, 12, 49, 10160, 67, 46, 57, 43, 2934, 72, 21335, 2932, 38, 789, 17, 37, 8863, 203, 3639, 804, 637, 7469, 12, 49, 10160, 67, 46, 57, 43, 2934, 72, 21335, 2932, 3378, 5528, 17, 37, 8863, 203, 3639, 804, 637, 7469, 12, 49, 10160, 67, 46, 57, 43, 2934, 72, 21335, 2932, 3378, 5528, 17, 38, 8863, 203, 3639, 804, 637, 7469, 12, 49, 10160, 67, 46, 57, 43, 2934, 72, 21335, 2932, 56, 3378, 40, 17, 37, 8863, 203, 3639, 804, 637, 7469, 12, 49, 10160, 67, 46, 57, 43, 2934, 72, 21335, 2932, 59, 38, 15988, 17, 37, 8863, 203, 3639, 804, 637, 7469, 12, 49, 10160, 67, 46, 57, 43, 2934, 72, 21335, 2932, 47, 10346, 17, 37, 8863, 203, 3639, 804, 637, 7469, 12, 49, 10160, 67, 46, 57, 43, 2934, 72, 21335, 2932, 62, 54, 60, 17, 37, 8863, 203, 203, 3639, 1758, 8526, 3778, 5071, 12645, 67, 1673, 273, 394, 1758, 8526, 12, 21, 1769, 203, 3639, 5071, 12645, 67, 1673, 63, 20, 65, 273, 611, 1285, 3865, 706, 67, 11846, 31, 203, 203, 3639, 1758, 8526, 3778, 5071, 12645, 273, 394, 1758, 8526, 12, 21, 1769, 203, 3639, 5071, 12645, 63, 20, 65, 273, 611, 1285, 3865, 706, 31, 2 ]
/// @author Adrian Lenard /// @title researchDAO - Collective intelligence for the research community /// @notice Purpose of this contract is to enable guild like operation for researchers, while enabling crowdfunding capital to accelerate research funding /// @dev All function calls are currently implemented without side effects pragma solidity ^0.5.0; import "./SafeMath.sol"; contract researchDAO { using SafeMath for uint; // Enabling contract to use SafeMath library for uint type operations // Global constants for constructor uint256 public globalVotingPeriod; // Default value is 30 days or 2.592e+6 seconds uint256 public globalRagequitPeriod; // Default value is 7 days or 604800 seconds uint256 public globalProposalDeposit; // Default value is 10 ETH uint256 public globalProcessingReward; // Default value is 0.1 ETH to incentivize processing. 10 means: 1/10 ETH per uint256 public globalSummoningTime; // The block.timestamp at contract deployment address payable public globalSummonerAddress; // The address which summoned the DAO uint8 public globalQuorum; // Default value is 50 for 50%, this sets the required participation for a proposal vote to pass uint8 public globalMajority; // Default value is 50 for 50%, this sets the number of required Yes votes for a vote to pass uint8 public globalDilutionBound; // Default value is 2 for 2x dilution, this prevents extreme dilution of members // Security limits thanks to Moloch DAO // These numbers are quite arbitrary; they are small enough to avoid overflows when doing calculations // with periods or shares, yet big enough to not limit reasonable use cases. uint256 constant MAX_VOTING_PERIOD_LENGTH = 10**18; // maximum length of voting period uint256 constant MAX_GRACE_PERIOD_LENGTH = 10**18; // maximum length of grace/ragequit period uint256 constant MAX_PROPOSAL_DEPOSIT = 10**18; // maximum number of proposal deposit that can be used uint256 constant MAX_NUMBER_OF_SHARES = 10**18; // maximum number of shares that can be minted uint256 constant MAX_PROCESS_REWARD = 10**18; // maximum number for processing reward that can be used uint256 constant MAX_INITIAL_SHARE = 10**18; // maximum number for initial share request that can be used uint256 constant MAX_FUNDING_GOAL = 10**18; // maximum number for funding that can be used uint8 constant MAX_QUORUM = 10**2; // maximum number for quorum that can be used uint8 constant MAX_MAJORITY = 10**2; // maximum number for majority that can be used uint8 constant MAX_DILUTION_BOUND = 10**2; // maximum number for dilution bound that can be used // Events event Summoned(address summoner, uint256 initialShares ); event SubmittedProposal( uint256 proposalIndex, address proposer, string title, bytes32 documentationAddress, bool isProposalOrApplication ); event ConfirmedApplication(uint256 proposalIndex, bool confirmation); event SubmittedVote(uint256 proposalIndex, address voter, uint8 vote); event ProcessedProposal(uint256 proposalIndex, bool didPass); event MemberJoinedGuild(address applicant, uint256 sharesMinted); event MemberReceivedNewShares(address applicant, uint256 sharesRequested); event MemberApplicationFailed(address applicant, uint256 noVotes, uint256 yesVotes, uint256 totalVotes); // These events need implementation event ExternalFundGuild(); event ExternalFundProposal(); event RageQuit(); // Guild governance - These variables are responsible for governance related values // Members struct Member { uint256 shares; // rDAO voting shares - voting power uint256 contribution; // Checking who offered how much when joining bool exists; // General switch to indicate if an address is already a member } mapping(address => Member) public members; // Storing member details in a mapping address[] public memberArray; // Member array // Votes enum Vote { Null, // default value Yes, No } // Proposal structure struct Proposal { // This struct serves as the framework for a proposal to be submitted uint256 proposalIndex; // the numeric ID of the proposal address payable proposer; // the address of the submitter address payable applicant; // the applicant address who would like to join uint256 sharesRequested; // shares requested for the proposed member string title; // simple title for the proposal, e.g.: Adrian L. new membership proposal bytes32 documentationAddress; // IPFS hash of the detailed documentation, e.g.: research project description uint256 fundingGoal; // amount of the required funding, coming from guild fund and external contributors bool isProposalOpen; // state of the proposal, default is open, closed in processProposal() call uint256 creationTimestamp; // now (block.timestamp) when proposal is submitted mapping(address => Vote) votesByMembers; // stores each members vote in a mapping uint256 yesVote; // # of Yes votes uint256 noVote; // # of No votes bool didPass; // result state of proposal, changed when calling processProposal() uint256 externalFundsCollected; // the amount received from external contributors bool isProposalOrApplication; // This is used for switching between member application and proposal for research. // [0 = proposal for research, 1 = new member application] } uint256 public proposalCounter; // Storing actual highest index for proposals - incremented upon submitProposal() Proposal[] public proposalQueue; // Storing proposals in an array for queuing mapping(address => uint256[]) public proposalsOfMembers; // Storing proposals for each member in an array // Storing the number of total shares at the moment of last Yes vote casted on a particular proposal - used for dilution bound mapping(uint256 => uint256) public maxTotalSharesAtYesVote; // Guild bank - These variables handle internal share allocations // Member shares are stored in the Member struct used in members mapping uint256 public rDAO_totalShareSupply; // Counting the total shares issued uint256 public totalSharesRequested; // Counting the total shares requested in the currently open proposals // Modifiers // memberOnly serves as the restriction modifier for calls to only allow members to call modifier memberOnly { require(members[msg.sender].shares > 0, "rDAO::memberOnly (modifier) - not a member of researchDAO"); _; } // isSummoner serves as the restriction modifier for calls to only allow summer to call - used in circuit breaker modifier isSummoner { require(msg.sender == globalSummonerAddress, "rDAO::isSummoner (modifier) - not the summoner of researchDAO"); _; } // Checking if proposal index is a valid proposal modifier isValidProposalIndex(uint256 _proposalIndex) { require(_proposalIndex > 0 , "rDAO::isValidProposalIndex (modifier) - input parameter must be higher than 0"); require(_proposalIndex <= proposalCounter, "rDAO::isValidProposalIndex (modifier) - proposalIndex is not valid, not existing proposal"); _; } // Checking if proposal is open modifier isProposalOpen(uint256 _proposalIndex) { require(proposalQueue[_proposalIndex.sub(1)].isProposalOpen == true, "rDAO::isProposalOpen (modifier) - Proposal is not open"); _; } // Implementing circuit breaker logic bool private stopped = false; modifier stopInEmergency { if(!stopped) _; } modifier onlyInEmergency { require(stopped); _; } // Circuit breaker switch to freeze functions - can be only called by the summoner function toggleContractFreeze() isSummoner public { stopped = !stopped; } // Summoning constructor /// @notice Constructor function for summoning the DAO /// @param _globalVotingPeriod The number which sets the voting period in seconds /// @param _globalRagequitPeriod The number which sets the ragequit period in seconds /// @param _globalProposalDeposit The number that sets the required deposit upon proposal submission /// @param _globalProcessingReward The number that sets the reward value when a member processes an ended proposal /// @param _initialSharesRequested The number of the shares the summoner receives when summoning the DAO /// @param _globalQuorum The quorum percentage required for a vote to pass /// @param _globalMajority The majority percentage that is requirement for Yes votes to pass /// @param _globalDilutionBound The number that prohibits extreme dilution of remaining members after a massive coordinated ragequit constructor( uint256 _globalVotingPeriod, uint256 _globalRagequitPeriod, uint256 _globalProposalDeposit, uint256 _globalProcessingReward, uint256 _initialSharesRequested, uint8 _globalQuorum, uint8 _globalMajority, uint8 _globalDilutionBound) public { // Checking summoning global constant values for security limits require(_globalVotingPeriod > 0, "rDAO::constructor - Voting period cannot be zero"); require(_globalVotingPeriod <= MAX_VOTING_PERIOD_LENGTH, "rDAO::constructor - Voting period is out of boundaries"); require(_globalRagequitPeriod > 0, "rDAO::constructor - Ragequit period cannot be zero"); require(_globalRagequitPeriod <= MAX_VOTING_PERIOD_LENGTH, "rDAO::constructor - Ragequit period is out of boundaries"); require(_globalProposalDeposit > 0, "rDAO::constructor - Proposal deposit cannot be negative or zero"); require(_globalProposalDeposit <= MAX_PROPOSAL_DEPOSIT, "rDAO::constructor - Proposal deposit is out of boundaries"); require(_globalProcessingReward > 0, "rDAO::constructor - Processing reward can't be zero. It serves as incentive"); require(_globalProcessingReward <= MAX_PROCESS_REWARD, "rDAO::constructor - Processing reward is out of boundaries"); require(_initialSharesRequested > 0, "rDAO::constructor - Initially requested share can't be zero."); require(_initialSharesRequested <= MAX_INITIAL_SHARE, "rDAO::constructor - Initially requested share is out of boundaries"); require(_globalQuorum > 0, "rDAO::constructor - Quorum can't be zero."); require(_globalQuorum <= MAX_QUORUM, "rDAO::constructor - Quorum is out of boundaries"); require(_globalMajority > 0, "rDAO::constructor - Majority can't be zero."); require(_globalMajority <= MAX_MAJORITY, "rDAO::constructor - Majority is out of boundaries"); require(_globalDilutionBound > 0, "rDAO::constructor - Dilution bound can't be zero."); require(_globalDilutionBound <= MAX_DILUTION_BOUND, "rDAO::constructor - Dilution bound is out of boundaries"); // Setting global constansts based on constructor parameters globalVotingPeriod = _globalVotingPeriod; globalRagequitPeriod = _globalRagequitPeriod; globalProposalDeposit = _globalProposalDeposit.mul(1e18); // Converting wei to ether globalProcessingReward = _globalProcessingReward.mul(1e18); // Converting wei to ether globalQuorum = _globalQuorum; globalMajority = _globalMajority; globalDilutionBound = _globalDilutionBound; globalSummonerAddress = msg.sender; // Storing summoner as a member memberArray.push(msg.sender); // Setting up initial founding member and storing his shares in members mapping members[msg.sender].shares = _initialSharesRequested; // Initializing share supply according to summoning parameters rDAO_totalShareSupply = members[msg.sender].shares; // Storing the timestamp of the summoning (now is alias for block.timestamp) globalSummoningTime = now; // Counter initialization proposalCounter = 0; // Emitting the corresponding event with the summoners address and the allocated share number emit Summoned(msg.sender, members[msg.sender].shares); } // Functions // --------- // submitProposal() when a member proposes something either for research or new membership application // submitVote() when a member casts a vote on a given proposal from within the DAO // processProposal() when a member finalizes a proposal by closing it and executing it based on the results // confirmApplication() when a proposed member confirms his application to avoid proposal of an applicant without consent // rageQuit() when a member ragequits and collects his funds based on rDAO share amount // externalFundProposal() when an external contributor funds a specific proposal // externalFundDAO() when an external contributor funds the DAO generally to let internal members decide over the fund /// @notice submitProposal function creates a new proposal submitted by an existing member /// @param _isProposalOrApplication Acts as a switch for deciding the proposal type: proposal for research OR proposal for new member application /// @param _applicant The address of the applying member /// @param _title The title of the submitted proposal /// @param _documentationAddress Hash address for the detailed documentation of the proposal /// @param _fundingGoal Funds required by the proposer to realize the research proposal /// @param _sharesRequested New shares minted for the applying member function submitProposal( bool _isProposalOrApplication, address payable _applicant, string memory _title, bytes32 _documentationAddress, uint256 _fundingGoal, uint256 _sharesRequested) public payable memberOnly stopInEmergency { // Setting up a switch to set if proposal open or not - used for application confirmation bool isOpen; // Checking if there is deposit sent with submitProposal function require(msg.value == globalProposalDeposit, "rDAO::submitProposal - Proposal deposit is not equal to requirement"); // Checking inputs for all types of proposal require(_documentationAddress.length > 0, "rDAO::submitProposal - Attached documentation is missing"); // IF proposal for research if ( _isProposalOrApplication == true ) { require(_fundingGoal > 0, "rDAO::submitProposal - Funding goal cannot be zero"); require(_fundingGoal <= MAX_FUNDING_GOAL, "rDAO::submitProposal - Funding goal is out of boundaries"); _sharesRequested = 0; // Zeroing out. Not needed when proposing a research isOpen = true; // Research proposal does not need confirmation } // IF proposal for new member application if( _isProposalOrApplication == false ) { require(_sharesRequested > 0, "rDAO::submitProposal - Shares requested cannot be zero"); // Calculating total shares requested plus total shares minted uint256 shareUpperBoundaries = _sharesRequested.add(rDAO_totalShareSupply).add(totalSharesRequested); require(shareUpperBoundaries <= MAX_NUMBER_OF_SHARES, "rDAO::submitProposal - Shares requested is out of boundaries"); _fundingGoal = 0; // Zeroing out. Not needed when proposing a new member isOpen = false; // Application proposal needs confirmation of applicant, therefore not open by default } // Copying current # for proposals and incrementing counter uint256 _proposalIndex = proposalCounter.add(1); proposalCounter = proposalCounter.add(1); // Creating proposal with fn parameters Proposal memory proposal = Proposal({ proposalIndex: _proposalIndex, proposer: msg.sender, applicant: _applicant, sharesRequested: _sharesRequested, title: _title, documentationAddress: _documentationAddress, fundingGoal: _fundingGoal, isProposalOpen: isOpen, creationTimestamp: now, yesVote: 0, noVote: 0, didPass: false, externalFundsCollected: 0, isProposalOrApplication: _isProposalOrApplication }); // Adding # of shares requested by the current proposal to totalSharesRequested if this is a member application if (!_isProposalOrApplication) { totalSharesRequested = totalSharesRequested.add(proposal.sharesRequested); } // Adding the created proposal to the proposal queue proposalQueue.push(proposal); // Adding proposal to proposalsOfMembers mapping array proposalsOfMembers[msg.sender].push(_proposalIndex); // Emitting related event emit SubmittedProposal(proposal.proposalIndex, msg.sender, proposal.title, proposal.documentationAddress, proposal.isProposalOrApplication); } /// @notice confirmApplication function to allow applicant confirm his application proposal /// @param _proposalIndex The index/ID of the proposal to vote on /// @param confirmation If confirms or not (true of false) function confirmApplication( uint256 _proposalIndex, bool confirmation ) public payable isValidProposalIndex(_proposalIndex) { require(_proposalIndex > 0 , "rDAO::confirmApplication - _proposalIndex input parameter must be higher than 0"); Proposal storage proposal = proposalQueue[_proposalIndex.sub(1)]; // Checking if confirmation has not been called by applicatan require(proposal.isProposalOrApplication == false, "rDAO::confirmApplication - Proposal is not an application"); // Checking if given proposal applicant is calling the function require(msg.sender == proposal.applicant, "rDAO::confirmApplication - Can only be called from applicant's address"); // Checking if confirmation has not been called by applicatan require(proposal.isProposalOpen == false, "rDAO::confirmApplication - Proposal has been already confirmed"); // Checking if the proposal voting period has ended bool isTimeLeft = now.sub(globalVotingPeriod) < proposal.creationTimestamp; require(isTimeLeft == true, "rDAO::confirmApplication - proposal period ended, no longer accepts confirmations."); // Setting confirmation status, true opens up the proposal, false leaves as is(false by default on submitProposal) if (confirmation == true) { proposal.isProposalOpen = confirmation; // Storing contribution value of the applicant members[msg.sender].contribution = msg.value; // Emitting relevant event emit ConfirmedApplication(_proposalIndex, confirmation); } else { // Delete proposal if applicant cancels delete proposalQueue[_proposalIndex.sub(1)]; } } /// @notice submitVote function to cast a vote on a given proposal /// @param _proposalIndex The index/ID of the proposal to vote on /// @param _uint8vote The vote - 0: Null, 1: Yes, 2: No function submitVote( uint256 _proposalIndex, uint8 _uint8vote ) public memberOnly isValidProposalIndex(_proposalIndex) isProposalOpen(_proposalIndex) { // require proposalIndex to a valid proposal using proposalCount // check timeframe: require VOTING_PERIOD - proposal.creationTimestamp > 0 // convert vote from uint to Vote struct to use with votesByMembers // store member and his vote in votesByMembers // mapping (address => Vote) votesByMembers; // stores each members vote in a mapping // store YesVote or NoVote and add up voter shares // emit Event submittedVote() Proposal storage proposal = proposalQueue[_proposalIndex.sub(1)]; // Checking if the proposal voting period has ended bool isTimeLeft = now.sub(globalVotingPeriod) < proposal.creationTimestamp; require(isTimeLeft == true, "rDAO::submitVote - proposal period ended, no longer accepts votes. Time to processProposal()"); // Checking that the input parameter _uint8vote is at most 3 and converting it into a Vote sturct require(_uint8vote < 3, "rDAO::submitVote - _uint8vote must be less than 3"); Vote vote = Vote(_uint8vote); // Checking if the member has voted already and storing the casted vote into votesByMembers require(proposal.votesByMembers[msg.sender] == Vote.Null , "rDAO::submitVote - member already voted"); proposal.votesByMembers[msg.sender] = vote; // Incrementing vote counters in proposal based on casted vote times the shares of the voting member if (vote == Vote.Yes) { proposal.yesVote = proposal.yesVote.add(members[msg.sender].shares); // Updating the number of total shares minted when member voted yes and share supply changed since last yes vote if (rDAO_totalShareSupply > maxTotalSharesAtYesVote[_proposalIndex]) { maxTotalSharesAtYesVote[_proposalIndex] = rDAO_totalShareSupply; } } else if (vote == Vote.No) { proposal.noVote = proposal.noVote.add(members[msg.sender].shares); } // Emitting the relevant event SubmittedVote() emit SubmittedVote(_proposalIndex, msg.sender, _uint8vote); } /// @notice processProposal processes an ended proposal and executes the proposed subject /// @param _proposalIndex The index/ID of the proposal to process /// @dev If proposal fails need to transfer back external contributions function processProposal(uint256 _proposalIndex) public memberOnly stopInEmergency isValidProposalIndex(_proposalIndex) //isProposalOpen(_proposalIndex) - unconfirmed proposals should be processable also, to return deposit { // check if proposal exists // check if proposal has ended // [check if quorum reached ?] 50% minimum // count votes and modify didPass // close proposal - isProposalOpen // based on isProposalOrApplication // - proposal: distribute funds or send back contributions // - application: distribute shares // return proposer ETH deposit // Storing proposal data Proposal storage proposal = proposalQueue[_proposalIndex.sub(1)]; // Checking if the proposal is voting period has passed bool isTimeLeft = now.sub(globalVotingPeriod) < proposal.creationTimestamp; require(isTimeLeft == false, "rDAO::processProposal - proposal voting period has not passed yet"); // Setting vote results based on summary of casted votes proposal.didPass = proposal.yesVote > proposal.noVote; // Setting proposal fail if dilution bound would be exceeded if (rDAO_totalShareSupply.mul(globalDilutionBound) < maxTotalSharesAtYesVote[_proposalIndex]) { proposal.didPass = false; } // Checking quorum and majority and setting proposal fail if either of them is not reached // Calculating total vote count uint256 totalVotes = proposal.yesVote.add(proposal.noVote); // Modify result to false if quorum is not reached proposal.didPass = totalVotes.mul(100) > rDAO_totalShareSupply.mul(globalQuorum); // Modifying result to false if majority is not reached proposal.didPass = proposal.yesVote.div(totalVotes).mul(100) > globalMajority; // Closing the proposal proposal.isProposalOpen = false; // Substracting requested share # of proposal from the current totalSharesRequested counter totalSharesRequested = totalSharesRequested.sub(proposal.sharesRequested); if (proposal.didPass == true) { // Execution logic based on proposal type [proposal vs. application] // IF proposal then send funds to proposer if didPass == true // IF application then add applicant to members and mint his shares // // Proposal if (proposal.isProposalOrApplication == true) { // Send out funds to proposer proposal.proposer.transfer(proposal.fundingGoal); } // Application else if (proposal.isProposalOrApplication == false) { // If member already exists if (members[proposal.applicant].exists) { // Adding new member shares members[proposal.applicant].shares.add(proposal.sharesRequested); // Emitting event emit MemberReceivedNewShares(proposal.applicant, proposal.sharesRequested); } // If member does not exist else { // Adding member to memberArray memberArray.push(proposal.applicant); // Adding member shares members[proposal.applicant].shares = proposal.sharesRequested; // Setting existance of member members[proposal.applicant].exists = true; // Emitting event of new joined member emit MemberJoinedGuild(proposal.applicant, proposal.sharesRequested); } } } else if (proposal.didPass == false) { // Pay back contribution made by proposal applicant proposal.applicant.transfer(members[proposal.applicant].contribution); // Pay back external contributors /// @dev Needs implementation if (proposal.isProposalOrApplication == false) { // Emit event of failed application emit MemberApplicationFailed(proposal.applicant, proposal.noVote, proposal.yesVote, proposal.noVote.add(proposal.yesVote)); } } // Return deposit to proposer proposal.proposer.transfer(globalProposalDeposit); // Emitting event emit ProcessedProposal(proposal.proposalIndex, proposal.didPass); // Paying processing reward to msg.sender // Reentrancy protection - executing all state changes before transferring funds msg.sender.call.value(globalProcessingReward); // The 2 lines below are failing due to probable gas //require(msg.sender.send(globalProcessingReward), "rDAO::processProposal - Reward Transfer"); //msg.sender.transfer(globalProcessingReward); } /// @notice Allows guild members to quit the guild if a voting would draw undesired outcome for them /// @dev not implemented yet function rageQuit() public memberOnly {} /// @notice Allows external contributors to fund a particular proposal /// @dev not implemented yet function externalFundProposal(uint256 _proposalIndex) public isValidProposalIndex(_proposalIndex) isProposalOpen(_proposalIndex) {} /// @notice Allows external contributors to fund the guild bank generally /// @dev not implemented yet function externalFundDAO() public {} // Getter functions function getMembers() public view returns(address[] memory) { return memberArray; } // Allow contract to receive external general contributions that goes to the guild funds ///@notice Fallback function for the contract function() external payable {} // Mortal function to shut down contract on upgrade and send all of its funds to the summoner adderess function shutDownDAO() public stopInEmergency isSummoner { selfdestruct(globalSummonerAddress); } }
maximum number for quorum that can be used
uint8 constant MAX_QUORUM = 10**2;
1,081,133
[ 1, 15724, 1300, 364, 31854, 716, 848, 506, 1399, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 11890, 28, 5381, 4552, 67, 3500, 916, 2799, 273, 1728, 636, 22, 31, 15604, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.4; interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } 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; } } 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"); } } } contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract MiningReward is Initializable { using SafeMath for uint256; using SafeERC20 for IERC20; bool internal _notEntered; /// @notice 奖励代币地址 address public rewardToken; /// @notice 管理员地址 address public admin; /// @notice 预备管理员地址 address public proposedAdmin; /// @notice 奖励设置时间 uint256 public datetime; /// @notice 用户奖励信息 /// @param amount 用户可提取的奖励数量 struct Balance { uint256 amount; } /// @notice 提币管理员地址 address public coinAdmin; /// @notice 预备提币管理员地址 address public proposedCoinAdmin; /// @notice 用户地址 => 用户奖励余额信息 mapping(address => Balance) public userBalance; /// @notice 事件:设置预备管理员 /// @param admin 管理员地址 /// @param proposedAdmin 预备管理员地址 event ProposeAdmin(address admin, address proposedAdmin); /// @notice 事件:Claim Admin /// @param oldAdmin 旧管理员地址 /// @param newAdmin 新管理员地址 event ClaimAdmin(address oldAdmin, address newAdmin); /// @notice 事件:管理员取出奖励代币(指定数量) /// @param amount 数量 event WithdrawRewardWithAmount(uint256 amount); /// @notice 事件:管理员取出奖励代币(全部取出) /// @param amount 数量 event WithdrawReward(uint256 amount); /// @notice 事件:管理员取出奖励代币(指定接收地址,全部取出) /// @param addr 接收地址 /// @param amount 数量 event WithdrawRewardToAddress(address addr, uint256 amount); /// @notice 事件:管理员取出奖励代币(指定接收地址,指定数量) /// @param addr 接收地址 /// @param amount 数量 event WithdrawRewardToAddressWithAmount(address addr, uint256 amount); /// @notice 事件:用户取出奖励 /// @param addr 用户地址 /// @param amount 数量 event ClaimReward(address addr, uint256 amount); /// @notice 事件:设置奖励代币 /// @param oldToken 老地址 /// @param newToken 新地址 event SetRewardToken(address oldToken, address newToken); /// @notice 事件:批量设置用户奖励 /// @param accounts 用户地址数组 /// @param amounts 奖励数量数组 /// @param datetime 时间戳 event BatchSet(address[] accounts, uint256[] amounts, uint256 datetime); /// @notice 事件:单独设置用户的奖励数量(修正情况下使用) /// @param account 用户地址 /// @param amount 奖励数量 event Set(address account, uint256 amount); /// @notice 初始化函数 /// @param _admin 管理员地址 /// @param _rewardToken 奖励代币地址 function initialize(address _admin, address _coinAdmin, address _rewardToken) public initializer { admin = _admin; coinAdmin = _coinAdmin; rewardToken = _rewardToken; _notEntered = true; } modifier onlyAdmin { require(msg.sender == admin, "Admin required"); _; } modifier onlyCoinAdmin { require(msg.sender == coinAdmin, "CoinAdmin required"); _; } modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; } /// @notice 设置奖励代币地址 /// @param _rewardToken 奖励代币地址 function setRewardToken(address _rewardToken) public onlyCoinAdmin { address oldToken = rewardToken; rewardToken = _rewardToken; emit SetRewardToken(oldToken, rewardToken); } /// @notice 设置预备管理员地址 /// @param _proposedAdmin 预备管理员地址 function proposeAdmin(address _proposedAdmin) public onlyAdmin { require(_proposedAdmin != address(0)); proposedAdmin = _proposedAdmin; emit ProposeAdmin(admin, _proposedAdmin); } /// @notice 预备管理员 claim 权限 function claimAdmin() public { require(msg.sender == proposedAdmin, "ProposedAdmin required"); address oldAdmin = admin; admin = proposedAdmin; proposedAdmin = address(0); emit ClaimAdmin(oldAdmin, admin); } /// @notice 设置预备管理员地址 /// @param _proposedCoinAdmin 预备管理员地址 function proposeCoinAdmin(address _proposedCoinAdmin) public onlyCoinAdmin { require(_proposedCoinAdmin != address(0)); proposedCoinAdmin = _proposedCoinAdmin; // emit ProposeAdmin(admin, _proposedCoinAdmin); } /// @notice 预备管理员 claim 权限 function claimCoinAdmin() public { require(msg.sender == proposedCoinAdmin, "proposedCoinAdmin required"); // address oldCoinAdmin = coinAdmin; coinAdmin = proposedCoinAdmin; proposedCoinAdmin = address(0); // emit ClaimAdmin(oldAdmin, admin); } /// @notice 管理员取出奖励代币的数量(可指定数量) /// @param amount 取出数量 function withdrawRewardWithAmount(uint256 amount) public onlyCoinAdmin { require( IERC20(rewardToken).balanceOf(address(this)) > 0, "No reward left" ); require(amount > 0, "Invalid amount"); IERC20(rewardToken).safeTransfer(admin, amount); emit WithdrawRewardWithAmount(amount); } /// @notice 管理员取出奖励代币的数量(全部取出) function withdrawReward() public onlyCoinAdmin { require( IERC20(rewardToken).balanceOf(address(this)) > 0, "No reward left" ); uint256 balance = checkRewardBalance(); IERC20(rewardToken).safeTransfer(admin, balance); emit WithdrawReward(balance); } /// @notice 管理员取出奖励代币的数量(全部取出,指定接收地址) /// @param addr 接收代币地址 function withdrawRewardToAddress(address addr) public onlyCoinAdmin { require( IERC20(rewardToken).balanceOf(address(this)) > 0, "No reward left" ); uint256 balance = checkRewardBalance(); IERC20(rewardToken).safeTransfer(addr, balance); emit WithdrawRewardToAddress(addr, balance); } /// @notice 管理员取出奖励代币的数量(全部取出,指定接收地址,指定数量) /// @param addr 接收代币地址 /// @param amount 取出数量 function withdrawRewardToAddressWithAmount(address addr, uint256 amount) public onlyCoinAdmin { require( IERC20(rewardToken).balanceOf(address(this)) > 0, "No reward left" ); IERC20(rewardToken).safeTransfer(addr, amount); emit WithdrawRewardToAddressWithAmount(addr, amount); } /// @notice 批量设置用户的奖励数量 /// @param accounts 用户地址数组 /// @param amount 奖励数量数组 /// @param _datetime 时间戳 function batchSet( address[] calldata accounts, uint256[] calldata amount, uint256 _datetime ) external onlyAdmin { require(_datetime > datetime, "Invalid time"); uint256 userCount = accounts.length; require(userCount == amount.length, "Invalid input"); for (uint256 i = 0; i < userCount; ++i) { userBalance[accounts[i]].amount = userBalance[accounts[i]] .amount .add(amount[i]); } datetime = _datetime; emit BatchSet(accounts, amount, _datetime); } /// @notice 单独设置用户的奖励数量(修正情况下使用) /// @param account 用户地址 /// @param amount 奖励数量 function set(address account, uint256 amount) external onlyAdmin { userBalance[account].amount = amount; emit Set(account, amount); } /// @notice 用户取出自己的挖矿奖励 function claimReward() public nonReentrant { uint256 claimAmount = userBalance[msg.sender].amount; require(claimAmount > 0, "No reward"); require( checkRewardBalance() >= claimAmount, "Insufficient rewardToken" ); userBalance[msg.sender].amount = 0; IERC20(rewardToken).safeTransfer(msg.sender, claimAmount); emit ClaimReward(msg.sender, claimAmount); } /// @notice 用户查看自己的可取资产 function checkBalance(address account) public view returns (uint256) { return userBalance[account].amount; } /// @notice 查看当前奖励代币余额 function checkRewardBalance() public view returns (uint256) { return IERC20(rewardToken).balanceOf(address(this)); } }
@notice 管理员取出奖励代币的数量(全部取出)
function withdrawReward() public onlyCoinAdmin { require( IERC20(rewardToken).balanceOf(address(this)) > 0, "No reward left" ); uint256 balance = checkRewardBalance(); IERC20(rewardToken).safeTransfer(admin, balance); emit WithdrawReward(balance); }
14,827,834
[ 1, 168, 111, 99, 168, 243, 233, 166, 244, 251, 166, 242, 249, 166, 234, 123, 166, 103, 249, 166, 237, 114, 165, 124, 101, 166, 121, 228, 168, 253, 231, 167, 248, 113, 170, 234, 242, 176, 125, 235, 166, 232, 106, 170, 230, 106, 166, 242, 249, 166, 234, 123, 176, 125, 236, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 17631, 1060, 1435, 1071, 1338, 27055, 4446, 288, 203, 3639, 2583, 12, 203, 5411, 467, 654, 39, 3462, 12, 266, 2913, 1345, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 405, 374, 16, 203, 5411, 315, 2279, 19890, 2002, 6, 203, 3639, 11272, 203, 3639, 2254, 5034, 11013, 273, 866, 17631, 1060, 13937, 5621, 203, 3639, 467, 654, 39, 3462, 12, 266, 2913, 1345, 2934, 4626, 5912, 12, 3666, 16, 11013, 1769, 203, 203, 3639, 3626, 3423, 9446, 17631, 1060, 12, 12296, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Sources flattened with hardhat v2.0.8 https://hardhat.org // File @openzeppelin/contracts/GSN/[email protected] // 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; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File @animoca/ethereum-contracts-core_library/contracts/access/[email protected] pragma solidity 0.6.8; contract WhitelistedOperators is Ownable { mapping(address => bool) internal _whitelistedOperators; event WhitelistedOperator(address operator, bool enabled); /// @notice Enable or disable address operator access /// @param operator address that will be given/removed operator right. /// @param enabled set whether the operator is enabled or disabled. function whitelistOperator(address operator, bool enabled) external onlyOwner { _whitelistedOperators[operator] = enabled; emit WhitelistedOperator(operator, enabled); } /// @notice check whether address `who` is given operator rights. /// @param who The address to query. /// @return whether the address is whitelisted operator function isOperator(address who) public view returns (bool) { return _whitelistedOperators[who]; } } // File @openzeppelin/contracts/introspection/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/introspection/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view 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/[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, 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/[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); } 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 @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected] /* https://github.com/OpenZeppelin/openzeppelin-contracts The MIT License (MIT) Copyright (c) 2016-2019 zOS Global Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.6.8; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @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 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); } // File @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected] /* https://github.com/OpenZeppelin/openzeppelin-contracts The MIT License (MIT) Copyright (c) 2016-2019 zOS Global Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.6.8; /** * @dev Interface for commonly used additional ERC20 interfaces */ interface IERC20Detailed { /** * @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 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. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() external view returns (uint8); } // File @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @dev Interface for additional ERC20 allowance features */ interface IERC20Allowance { /** * @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) external returns (bool); /** * @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) external returns (bool); } // File @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected] /* https://github.com/OpenZeppelin/openzeppelin-contracts The MIT License (MIT) Copyright (c) 2016-2019 zOS Global Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.6.8; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ abstract contract ERC20 is ERC165, Context, IERC20, IERC20Detailed, IERC20Allowance { using SafeMath for uint256; using Address for address; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 internal _totalSupply; constructor() internal { _registerInterface(type(IERC20).interfaceId); _registerInterface(type(IERC20Detailed).interfaceId); _registerInterface(type(IERC20Allowance).interfaceId); // ERC20Name interfaceId: bytes4(keccak256("name()")) _registerInterface(0x06fdde03); // ERC20Symbol interfaceId: bytes4(keccak256("symbol()")) _registerInterface(0x95d89b41); // ERC20Decimals interfaceId: bytes4(keccak256("decimals()")) _registerInterface(0x313ce567); } /////////////////////////////////////////// ERC20 /////////////////////////////////////// /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /////////////////////////////////////////// ERC20Allowance /////////////////////////////////////// /** * @dev See {IERC20Allowance-increaseAllowance}. */ function increaseAllowance( address spender, uint256 addedValue ) public virtual override returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev See {IERC20Allowance-decreaseAllowance}. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public virtual override returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /////////////////////////////////////////// Internal Functions /////////////////////////////////////// /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /////////////////////////////////////////// Hooks /////////////////////////////////////// /** * @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. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; abstract contract ERC20WithOperators is ERC20, WhitelistedOperators { /** * NOTICE * This override will allow *any* whitelisted operator to be able to * transfer unresitricted amounts of ERC20WithOperators-based tokens from 'sender' * to 'recipient'. Care must be taken to ensure to integrity of the * whitelisted operator list. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { address msgSender = _msgSender(); // bypass the internal allowance manipulation and checks for the // whitelisted operator (i.e. _msgSender()). as a side-effect, the // 'Approval' event will not be emitted since the allowance was not // updated. if (!isOperator(msgSender)) { _approve(sender, msgSender, allowance(sender, msgSender).sub(amount)); } _transfer(sender, recipient, amount); return true; } function allowance(address owner, address spender) public override view returns (uint256) { if (isOperator(spender)) { // allow the front-end to determine whether or not an approval is // necessary, given that the whitelisted operator status of the // spender is unknown. A call to WhitelistedOperators::isOperator() // is more direct, but we want to expose a mechanism by which to // check through the ERC20 interface. return type(uint256).max; } else { return super.allowance(owner, spender); } } function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) { if (isOperator(spender)) { // bypass the internal allowance manipulation and checks for the // whitelisted operator (i.e. spender). as a side-effect, the // 'Approval' event will not be emitted since the allowance was not // updated. return true; } else { return super.increaseAllowance(spender, addedValue); } } function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) { if (isOperator(spender)) { // bypass the internal allowance manipulation and checks for the // whitelisted operator (i.e. spender). as a side-effect, the // 'Approval' event will not be emitted since the allowance was not // updated. return true; } else { return super.decreaseAllowance(spender, subtractedValue); } } function _approve(address owner, address spender, uint256 value) internal override { if (isOperator(spender)) { // bypass the internal allowance manipulation and checks for the // whitelisted operator (i.e. spender). as a side-effect, the // 'Approval' event will not be emitted since the allowance was not // updated. return; } else { super._approve(owner, spender, value); } } } // File contracts/solc-0.6/token/ERC20/GAMEE.sol pragma solidity 0.6.8; /** * @title GAMEE */ contract GAMEE is ERC20WithOperators { // solhint-disable-next-line const-name-snakecase string public constant override name = "GAMEE"; // solhint-disable-next-line const-name-snakecase string public constant override symbol = "GMEE"; // solhint-disable-next-line const-name-snakecase uint8 public constant override decimals = 18; constructor(address[] memory holders, uint256[] memory amounts) public ERC20WithOperators() { require(holders.length == amounts.length, "GAMEE: inconsistent arrays"); for (uint256 i = 0; i != holders.length; ++i) { _mint(holders[i], amounts[i]); } } }
* @title GAMEE/ solhint-disable-next-line const-name-snakecase solhint-disable-next-line const-name-snakecase solhint-disable-next-line const-name-snakecase
contract GAMEE is ERC20WithOperators { string public constant override name = "GAMEE"; string public constant override symbol = "GMEE"; uint8 public constant override decimals = 18; constructor(address[] memory holders, uint256[] memory amounts) public ERC20WithOperators() { require(holders.length == amounts.length, "GAMEE: inconsistent arrays"); for (uint256 i = 0; i != holders.length; ++i) { _mint(holders[i], amounts[i]); } } constructor(address[] memory holders, uint256[] memory amounts) public ERC20WithOperators() { require(holders.length == amounts.length, "GAMEE: inconsistent arrays"); for (uint256 i = 0; i != holders.length; ++i) { _mint(holders[i], amounts[i]); } } }
14,811,257
[ 1, 43, 1642, 41, 19, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 1866, 17, 529, 17, 8134, 581, 557, 448, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 1866, 17, 529, 17, 8134, 581, 557, 448, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 1866, 17, 529, 17, 8134, 581, 557, 448, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 611, 1642, 41, 353, 4232, 39, 3462, 1190, 24473, 288, 203, 565, 533, 1071, 5381, 3849, 508, 273, 315, 43, 1642, 41, 14432, 203, 565, 533, 1071, 5381, 3849, 3273, 273, 315, 43, 958, 41, 14432, 203, 565, 2254, 28, 1071, 5381, 3849, 15105, 273, 6549, 31, 203, 203, 203, 565, 3885, 12, 2867, 8526, 3778, 366, 4665, 16, 2254, 5034, 8526, 3778, 30980, 13, 1071, 4232, 39, 3462, 1190, 24473, 1435, 288, 203, 3639, 2583, 12, 9000, 18, 2469, 422, 30980, 18, 2469, 16, 315, 43, 1642, 41, 30, 27403, 5352, 8863, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 480, 366, 4665, 18, 2469, 31, 965, 77, 13, 288, 203, 5411, 389, 81, 474, 12, 9000, 63, 77, 6487, 30980, 63, 77, 19226, 203, 3639, 289, 203, 565, 289, 203, 565, 3885, 12, 2867, 8526, 3778, 366, 4665, 16, 2254, 5034, 8526, 3778, 30980, 13, 1071, 4232, 39, 3462, 1190, 24473, 1435, 288, 203, 3639, 2583, 12, 9000, 18, 2469, 422, 30980, 18, 2469, 16, 315, 43, 1642, 41, 30, 27403, 5352, 8863, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 480, 366, 4665, 18, 2469, 31, 965, 77, 13, 288, 203, 5411, 389, 81, 474, 12, 9000, 63, 77, 6487, 30980, 63, 77, 19226, 203, 3639, 289, 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 ]
./full_match/3/0xEA728948C55E028DAaa9f3149c7839fe2851cD7F/sources/browser/Axiatoken2.sol
if the person making the transaction is whitelisted, the no burn on the transaction
if(mapAddress_Whitelisted[msg.sender]){
8,225,526
[ 1, 430, 326, 6175, 10480, 326, 2492, 353, 26944, 16, 326, 1158, 18305, 603, 326, 2492, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 12, 1458, 1887, 67, 18927, 329, 63, 3576, 18, 15330, 5717, 95, 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 ]
pragma solidity ^0.4.24; import "./../utils/LinkedIdList.sol"; import "openzeppelin-solidity/math/SafeMath.sol"; contract MultiTokenModule { using SafeMath for uint; event AddRelatedToken( address owner, uint256 keyId, uint256 tokenId, uint256 rate ); event RemoveRelatedToken( address owner, uint256 keyId, uint256 tokenId ); event UpdateRelatedToken( address owner, uint256 keyId, uint256 tokenId, uint256 rate ); event ChangeBaseToken( address owner, uint256 keyId, uint256 tokenId ); // Mapping from key id to exchange rate of the token mapping(uint256 => mapping(uint256 => uint256)) private keyIdTokensRate; // Mapping from key id to the base token mapping(uint256 => uint256) private baseToken; // decimals of rate uint8 private _rateDecimals; // Mapping from keyId to token Ids LinkedIdList private tokenIdList; constructor() public { _rateDecimals = 4; tokenIdList = new LinkedIdList(); } /// @return the number of decimals of the rate. function rateDecimals() public view returns(uint8) { return _rateDecimals; } /// @dev Aadd a token id to the list of a given key id /// @param _keyId key id of the tokens list /// @param _tokenId id of the token to be added to the tokens list of the given key id /// @param _rate rate function _addRelatedToken( uint256 _keyId, uint256 _tokenId, uint256 _rate ) internal { require(!_isRegisteredToken(_keyId, _tokenId)); // set base token if (tokenIdList.totalOf(_keyId) == 0) { _changeBaseToken(_keyId, _tokenId); } // set id tokenIdList.add(_keyId, _tokenId); // set rate keyIdTokensRate[_keyId][_tokenId] = _rate; emit AddRelatedToken(msg.sender, _keyId, _tokenId, _rate); } /// @dev Remove a token ID from the list of a key id /// @param _keyId key id of the tokens list /// @param _tokenId id of the token to be added to the tokens list of the given key id function _removeRelatedToken(uint256 _keyId, uint256 _tokenId) internal { require(_isRegisteredToken(_keyId, _tokenId)); require(_baseTokenOf(_keyId) != _tokenId); tokenIdList.remove(_keyId, _tokenId); // clear rate keyIdTokensRate[_keyId][_tokenId] = 0; emit RemoveRelatedToken(msg.sender, _keyId, _tokenId); } /// @dev Update a token info from the list of a key id /// @param _keyId key id of the tokens list /// @param _tokenId id of the token to be updated /// @param _rate rate function _updateRelatedToken( uint256 _keyId, uint256 _tokenId, uint256 _rate, bool isBase ) internal { require(_isRegisteredToken(_keyId, _tokenId)); if (isBase) { // set base token _changeBaseToken(_keyId, _tokenId); } // set rate keyIdTokensRate[_keyId][_tokenId] = _rate; emit UpdateRelatedToken(msg.sender, _keyId, _tokenId, _rate); } /// @dev Get ths exchange rate of the token id /// @param _keyId key id of the tokens list /// @param _tokenId id of the token to be added to the tokens list of the given key id function _rateOf(uint256 _keyId, uint256 _tokenId) internal view returns (uint256) { require(_isRegisteredToken(_keyId, _tokenId)); return keyIdTokensRate[_keyId][_tokenId]; } /// @dev Returns whether the specified token id registered /// @param _keyId key id of the token id list /// @param _tokenId id of the token to be added to the token id list of the given key id /// @return whether the token registered function _isRegisteredToken(uint256 _keyId, uint256 _tokenId) internal view returns (bool) { // return tokenRegistrationStatus[_keyId][_tokenId]; return tokenIdList.exists(_keyId, _tokenId); } /// @dev Returns base token id /// @param _keyId key id of the token id list /// @return token id function _baseTokenOf(uint256 _keyId) internal view returns (uint256) { return baseToken[_keyId]; } /// @dev Returns token id list of the specified key id /// @param _keyId key id of the token id list /// @return token id list function _tokensOfKey(uint256 _keyId) internal view returns (uint256[]) { return tokenIdList.valuesOf(_keyId); } /// @dev Calculate amount by exchange rate /// @param _keyId key id of the token id list /// @param _tokenId id of the token to be added to the tokens list of the given key id /// @param _amout amount function _exchangedAmountOf( uint256 _keyId, uint256 _tokenId, uint256 _amout ) internal view returns (uint256) { // calculate amount if(_baseTokenOf(_keyId) != _tokenId) { return _amout .mul(_rateOf(_keyId, _tokenId)) .div(10 ** uint256(rateDecimals())); } else { return _amout; } } /// @dev Update status whether the token is base /// @param _keyId key id of the tokens list /// @param _tokenId id of the token to be added to the tokens list of the given key id function _changeBaseToken(uint256 _keyId, uint256 _tokenId) private { baseToken[_keyId] = _tokenId; emit ChangeBaseToken(msg.sender, _keyId, _tokenId); } }
@dev Calculate amount by exchange rate @param _keyId key id of the token id list @param _tokenId id of the token to be added to the tokens list of the given key id @param _amout amount calculate amount
function _exchangedAmountOf( uint256 _keyId, uint256 _tokenId, uint256 _amout ) internal view returns (uint256) { if(_baseTokenOf(_keyId) != _tokenId) { return _amout .mul(_rateOf(_keyId, _tokenId)) .div(10 ** uint256(rateDecimals())); return _amout; } }
6,428,739
[ 1, 8695, 3844, 635, 7829, 4993, 225, 389, 856, 548, 498, 612, 434, 326, 1147, 612, 666, 225, 389, 2316, 548, 612, 434, 326, 1147, 358, 506, 3096, 358, 326, 2430, 666, 434, 326, 864, 498, 612, 225, 389, 301, 659, 3844, 4604, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 389, 338, 6703, 6275, 951, 12, 203, 3639, 2254, 5034, 389, 856, 548, 16, 203, 3639, 2254, 5034, 389, 2316, 548, 16, 203, 3639, 2254, 5034, 389, 301, 659, 203, 565, 262, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 24899, 1969, 1345, 951, 24899, 856, 548, 13, 480, 389, 2316, 548, 13, 288, 203, 5411, 327, 389, 301, 659, 203, 7734, 263, 16411, 24899, 5141, 951, 24899, 856, 548, 16, 389, 2316, 548, 3719, 203, 7734, 263, 2892, 12, 2163, 2826, 2254, 5034, 12, 5141, 31809, 1435, 10019, 203, 5411, 327, 389, 301, 659, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "./ERC1155AfterTransfer.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; abstract contract ERC1155Enumerable is ERC1155AfterTransfer { using EnumerableSet for EnumerableSet.UintSet; mapping(address => EnumerableSet.UintSet) internal _accountTokens; function _afterTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._afterTokenTransfer(operator, from, to, ids, amounts, data); _updateAccountsTokens(from, to, ids); } /** * @dev After any transfer, checks if from and to accountTokens should be updated * this function can be very expensive, it reads the storage a lot, be careful why you make use of this. * * @param from the address that lost tokens * @param to the address that fained tokens * @param ids the ids that have been transfered */ function _updateAccountsTokens( address from, address to, uint256[] memory ids ) internal virtual { bool checkAddressFrom = from != address(0); bool checkAddressTo = to != address(0); for (uint256 i; i < ids.length; i++) { // if from has balance 0, remove from accountTokens if (checkAddressFrom && balanceOf(from, ids[i]) == 0) { _accountTokens[from].remove(ids[i]); } // here we always have to try to add it if the balance > 0 // we can not use amounts[i] because a transferBatch could contain // twice the same id, and amounts[i] would never match the current balance // we still have to check balance though, because transfers can be of 0 (yes...) if (checkAddressTo && balanceOf(to, ids[i]) > 0) { _accountTokens[to].add(ids[i]); } } } /** * @dev get the number of different tokens own by an account * * @param account the account address */ function getAccountTokensCount(address account) public view virtual returns (uint256) { return _accountTokens[account].length(); } /** * @dev get the token owned at index {index} of account * This is using EnumerableSet so order can change at any time with inserts and removals * * * @param account the account address * @param index the index in the list */ function getAccountTokensByIndex(address account, uint256 index) public view virtual returns (uint256) { return _accountTokens[account].at(index); } /** * @dev Get a paginated list of an account tokens * This is a pretty expensive function and SHOULD be only used externally * or if you really know what you're doing. * * @param account The account we want the list of tokens * @param cursor Index to start at * @param limit how many we want per page * * @return tokenIds the token Ids * @return amounts the token balances * @return nextCursor next cursor to use */ function getAccountTokensPaginated( address account, uint256 cursor, uint256 limit ) public view virtual returns ( uint256[] memory tokenIds, uint256[] memory amounts, uint256 nextCursor ) { uint256 itemsCount = getAccountTokensCount(account); uint256 length = limit; if (length > itemsCount - cursor) { length = itemsCount - cursor; } tokenIds = new uint256[](length); amounts = new uint256[](length); for (uint256 i; i < length; i++) { tokenIds[i] = getAccountTokensByIndex(account, cursor + i); amounts[i] = balanceOf(account, tokenIds[i]); } return (tokenIds, amounts, cursor + length); } }
* @dev Get a paginated list of an account tokens This is a pretty expensive function and SHOULD be only used externally or if you really know what you're doing. @param account The account we want the list of tokens @param cursor Index to start at @param limit how many we want per page @return tokenIds the token Ids @return amounts the token balances @return nextCursor next cursor to use/
function getAccountTokensPaginated( address account, uint256 cursor, uint256 limit ) public view virtual returns ( uint256[] memory tokenIds, uint256[] memory amounts, uint256 nextCursor ) { uint256 itemsCount = getAccountTokensCount(account); uint256 length = limit; if (length > itemsCount - cursor) { length = itemsCount - cursor; } tokenIds = new uint256[](length); amounts = new uint256[](length); for (uint256 i; i < length; i++) { tokenIds[i] = getAccountTokensByIndex(account, cursor + i); amounts[i] = balanceOf(account, tokenIds[i]); } return (tokenIds, amounts, cursor + length); }
13,058,515
[ 1, 967, 279, 25373, 666, 434, 392, 2236, 2430, 1220, 353, 279, 7517, 19326, 445, 471, 6122, 31090, 506, 1338, 1399, 18885, 1230, 578, 309, 1846, 8654, 5055, 4121, 1846, 4565, 9957, 18, 225, 2236, 1021, 2236, 732, 2545, 326, 666, 434, 2430, 225, 3347, 3340, 358, 787, 622, 225, 1800, 3661, 4906, 732, 2545, 1534, 1363, 327, 1147, 2673, 326, 1147, 29085, 327, 30980, 326, 1147, 324, 26488, 327, 1024, 6688, 1024, 3347, 358, 999, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 23393, 5157, 10156, 7458, 12, 203, 3639, 1758, 2236, 16, 203, 3639, 2254, 5034, 3347, 16, 203, 3639, 2254, 5034, 1800, 203, 565, 262, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 1135, 261, 203, 5411, 2254, 5034, 8526, 3778, 1147, 2673, 16, 203, 5411, 2254, 5034, 8526, 3778, 30980, 16, 203, 5411, 2254, 5034, 1024, 6688, 203, 3639, 262, 203, 565, 288, 203, 3639, 2254, 5034, 1516, 1380, 273, 23393, 5157, 1380, 12, 4631, 1769, 203, 3639, 2254, 5034, 769, 273, 1800, 31, 203, 3639, 309, 261, 2469, 405, 1516, 1380, 300, 3347, 13, 288, 203, 5411, 769, 273, 1516, 1380, 300, 3347, 31, 203, 3639, 289, 203, 203, 3639, 1147, 2673, 273, 394, 2254, 5034, 8526, 12, 2469, 1769, 203, 3639, 30980, 273, 394, 2254, 5034, 8526, 12, 2469, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 769, 31, 277, 27245, 288, 203, 5411, 1147, 2673, 63, 77, 65, 273, 23393, 5157, 21268, 12, 4631, 16, 3347, 397, 277, 1769, 203, 5411, 30980, 63, 77, 65, 273, 11013, 951, 12, 4631, 16, 1147, 2673, 63, 77, 19226, 203, 3639, 289, 203, 203, 3639, 327, 261, 2316, 2673, 16, 30980, 16, 3347, 397, 769, 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 ]
./partial_match/56/0x630577e10b90BED6808407156428c2435d8f5015/sources/yALPHA.sol
Update actual values of accounts and distribute on transfer, automatic getter and exec
function yALPHAReward(uint256 valueToken) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 valueyALPHA,,,,) = _getValues(valueToken); _yALPHAValueOwned[sender] = _yALPHAValueOwned[sender].sub(valueyALPHA); _maxSupplyGen = _maxSupplyGen.sub(valueyALPHA); _CurTotalFee = _CurTotalFee.add(valueToken); }
11,133,127
[ 1, 1891, 3214, 924, 434, 9484, 471, 25722, 603, 7412, 16, 5859, 7060, 471, 1196, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 677, 19799, 985, 359, 1060, 12, 11890, 5034, 460, 1345, 13, 1071, 288, 203, 3639, 1758, 5793, 273, 389, 3576, 12021, 5621, 203, 3639, 2583, 12, 5, 67, 291, 16461, 63, 15330, 6487, 315, 16461, 6138, 2780, 745, 333, 445, 8863, 203, 3639, 261, 11890, 5034, 460, 93, 26313, 30495, 13, 273, 389, 588, 1972, 12, 1132, 1345, 1769, 203, 3639, 389, 93, 26313, 620, 5460, 329, 63, 15330, 65, 273, 389, 93, 26313, 620, 5460, 329, 63, 15330, 8009, 1717, 12, 1132, 93, 26313, 1769, 203, 3639, 389, 1896, 3088, 1283, 7642, 273, 389, 1896, 3088, 1283, 7642, 18, 1717, 12, 1132, 93, 26313, 1769, 203, 3639, 389, 2408, 5269, 14667, 273, 389, 2408, 5269, 14667, 18, 1289, 12, 1132, 1345, 1769, 203, 565, 289, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0xe72462A20dD5a0C2d2cBA1A5A29B1CeA4464F8A4/sources/browser/CommonWealth.sol
* @dev Calculates the amount that has already vested. @param token ERC20 token which is being vested/
function _vestedAmount(IERC20 token) private view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(_released[address(token)]); if (block.timestamp < _cliff) { return 0; return totalBalance; return totalBalance.mul(block.timestamp.sub(_start)).div(_duration); uint256 daysPassed = block.timestamp.sub(_start).div(secondsPerDay); uint256 amount0 = totalBalance.mul(_immedReleasedAmount).div(oneHundredMillion); uint256 amount1 = totalBalance.mul(_dailyReleasedAmount).mul(daysPassed).div(oneHundredMillion); uint256 amount2 = totalBalance.mul(_dailyReleasedNLAmount.mul(daysPassed.mul(daysPassed).mul(daysPassed))).div(oneHundredMillion); uint256 vestedAmount = amount0.add(amount1).add(amount2); return totalBalance < vestedAmount ? totalBalance : vestedAmount; } }
8,103,979
[ 1, 10587, 326, 3844, 716, 711, 1818, 331, 3149, 18, 225, 1147, 4232, 39, 3462, 1147, 1492, 353, 3832, 331, 3149, 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, 389, 90, 3149, 6275, 12, 45, 654, 39, 3462, 1147, 13, 3238, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 783, 13937, 273, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 2078, 13937, 273, 783, 13937, 18, 1289, 24899, 9340, 72, 63, 2867, 12, 2316, 13, 19226, 203, 203, 3639, 309, 261, 2629, 18, 5508, 411, 389, 830, 3048, 13, 288, 203, 5411, 327, 374, 31, 203, 5411, 327, 2078, 13937, 31, 203, 5411, 327, 2078, 13937, 18, 16411, 12, 2629, 18, 5508, 18, 1717, 24899, 1937, 13, 2934, 2892, 24899, 8760, 1769, 203, 5411, 2254, 5034, 4681, 22530, 273, 1203, 18, 5508, 18, 1717, 24899, 1937, 2934, 2892, 12, 7572, 2173, 4245, 1769, 203, 5411, 2254, 5034, 3844, 20, 273, 2078, 13937, 18, 16411, 24899, 381, 2937, 26363, 6275, 2934, 2892, 12, 476, 44, 1074, 1118, 49, 737, 285, 1769, 203, 5411, 2254, 5034, 3844, 21, 273, 2078, 13937, 18, 16411, 24899, 26790, 26363, 6275, 2934, 16411, 12, 9810, 22530, 2934, 2892, 12, 476, 44, 1074, 1118, 49, 737, 285, 1769, 203, 5411, 2254, 5034, 3844, 22, 273, 2078, 13937, 18, 16411, 24899, 26790, 26363, 50, 2534, 4778, 18, 16411, 12, 9810, 22530, 18, 16411, 12, 9810, 22530, 2934, 16411, 12, 9810, 22530, 3719, 2934, 2892, 12, 476, 44, 1074, 1118, 49, 737, 285, 1769, 203, 5411, 2254, 5034, 331, 3149, 6275, 273, 3844, 20, 18, 1289, 12, 8949, 21, 2934, 1289, 12, 8949, 22, 1769, 203, 5411, 327, 2078, 13937, 411, 331, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.1; import "./OffchainAggregator.sol"; import "./SimpleReadAccessController.sol"; /** * @notice Wrapper of OffchainAggregator which checks read access on Aggregator-interface methods */ contract AccessControlledOffchainAggregator is OffchainAggregator, SimpleReadAccessController { constructor( uint32 _maximumGasPrice, uint32 _reasonableGasPrice, uint32 _microLinkPerEth, uint32 _linkGweiPerObservation, uint32 _linkGweiPerTransmission, address _link, address _validator, int192 _minAnswer, int192 _maxAnswer, AccessControllerInterface _billingAccessController, AccessControllerInterface _requesterAccessController, uint8 _decimals, string memory description ) OffchainAggregator( _maximumGasPrice, _reasonableGasPrice, _microLinkPerEth, _linkGweiPerObservation, _linkGweiPerTransmission, _link, _validator, _minAnswer, _maxAnswer, _billingAccessController, _requesterAccessController, _decimals, description ) { } /* * v2 Aggregator interface */ /// @inheritdoc OffchainAggregator function latestAnswer() public override view checkAccess() returns (int256) { return super.latestAnswer(); } /// @inheritdoc OffchainAggregator function latestTimestamp() public override view checkAccess() returns (uint256) { return super.latestTimestamp(); } /// @inheritdoc OffchainAggregator function latestRound() public override view checkAccess() returns (uint256) { return super.latestRound(); } /// @inheritdoc OffchainAggregator function getAnswer(uint256 _roundId) public override view checkAccess() returns (int256) { return super.getAnswer(_roundId); } /// @inheritdoc OffchainAggregator function getTimestamp(uint256 _roundId) public override view checkAccess() returns (uint256) { return super.getTimestamp(_roundId); } /* * v3 Aggregator interface */ /// @inheritdoc OffchainAggregator function description() public override view checkAccess() returns (string memory) { return super.description(); } /// @inheritdoc OffchainAggregator function getRoundData(uint80 _roundId) public override view checkAccess() returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return super.getRoundData(_roundId); } /// @inheritdoc OffchainAggregator function latestRoundData() public override view checkAccess() returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return super.latestRoundData(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./AccessControllerInterface.sol"; import "./AggregatorV2V3Interface.sol"; import "./AggregatorValidatorInterface.sol"; import "./LinkTokenInterface.sol"; import "./Owned.sol"; import "./OffchainAggregatorBilling.sol"; /** * @notice Onchain verification of reports from the offchain reporting protocol * @dev For details on its operation, see the offchain reporting protocol design * @dev doc, which refers to this contract as simply the "contract". */ contract OffchainAggregator is Owned, OffchainAggregatorBilling, AggregatorV2V3Interface { uint256 constant private maxUint32 = (1 << 32) - 1; // Storing these fields used on the hot path in a HotVars variable reduces the // retrieval of all of them to a single SLOAD. If any further fields are // added, make sure that storage of the struct still takes at most 32 bytes. struct HotVars { // Provides 128 bits of security against 2nd pre-image attacks, but only // 64 bits against collisions. This is acceptable, since a malicious owner has // easier way of messing up the protocol than to find hash collisions. bytes16 latestConfigDigest; uint40 latestEpochAndRound; // 32 most sig bits for epoch, 8 least sig bits for round // Current bound assumed on number of faulty/dishonest oracles participating // in the protocol, this value is referred to as f in the design uint8 threshold; // Chainlink Aggregators expose a roundId to consumers. The offchain reporting // protocol does not use this id anywhere. We increment it whenever a new // transmission is made to provide callers with contiguous ids for successive // reports. uint32 latestAggregatorRoundId; } HotVars internal s_hotVars; // Transmission records the median answer from the transmit transaction at // time timestamp struct Transmission { int192 answer; // 192 bits ought to be enough for anyone uint64 timestamp; } mapping(uint32 /* aggregator round ID */ => Transmission) internal s_transmissions; // incremented each time a new config is posted. This count is incorporated // into the config digest, to prevent replay attacks. uint32 internal s_configCount; uint32 internal s_latestConfigBlockNumber; // makes it easier for offchain systems // to extract config from logs. // Lowest answer the system is allowed to report in response to transmissions int192 immutable public minAnswer; // Highest answer the system is allowed to report in response to transmissions int192 immutable public maxAnswer; /* * @param _maximumGasPrice highest gas price for which transmitter will be compensated * @param _reasonableGasPrice transmitter will receive reward for gas prices under this value * @param _microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units * @param _linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units * @param _linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units * @param _link address of the LINK contract * @param _validator address of validator contract (must satisfy AggregatorValidatorInterface) * @param _minAnswer lowest answer the median of a report is allowed to be * @param _maxAnswer highest answer the median of a report is allowed to be * @param _billingAccessController access controller for billing admin functions * @param _requesterAccessController access controller for requesting new rounds * @param _decimals answers are stored in fixed-point format, with this many digits of precision * @param _description short human-readable description of observable this contract's answers pertain to */ constructor( uint32 _maximumGasPrice, uint32 _reasonableGasPrice, uint32 _microLinkPerEth, uint32 _linkGweiPerObservation, uint32 _linkGweiPerTransmission, address _link, address _validator, int192 _minAnswer, int192 _maxAnswer, AccessControllerInterface _billingAccessController, AccessControllerInterface _requesterAccessController, uint8 _decimals, string memory _description ) OffchainAggregatorBilling(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth, _linkGweiPerObservation, _linkGweiPerTransmission, _link, _billingAccessController ) { decimals = _decimals; s_description = _description; setRequesterAccessController(_requesterAccessController); setValidator(_validator); minAnswer = _minAnswer; maxAnswer = _maxAnswer; } /* * Config logic */ /** * @notice triggers a new run of the offchain reporting protocol * @param previousConfigBlockNumber block in which the previous config was set, to simplify historic analysis * @param configCount ordinal number of this config setting among all config settings over the life of this contract * @param signers ith element is address ith oracle uses to sign a report * @param transmitters ith element is address ith oracle uses to transmit a report via the transmit method * @param threshold maximum number of faulty/dishonest oracles the protocol can tolerate while still working correctly * @param encodedConfigVersion version of the serialization format used for "encoded" parameter * @param encoded serialized data used by oracles to configure their offchain operation */ event ConfigSet( uint32 previousConfigBlockNumber, uint64 configCount, address[] signers, address[] transmitters, uint8 threshold, uint64 encodedConfigVersion, bytes encoded ); // Reverts transaction if config args are invalid modifier checkConfigValid ( uint256 _numSigners, uint256 _numTransmitters, uint256 _threshold ) { require(_numSigners <= maxNumOracles, "too many signers"); require(_threshold > 0, "threshold must be positive"); require( _numSigners == _numTransmitters, "oracle addresses out of registration" ); require(_numSigners > 3*_threshold, "faulty-oracle threshold too high"); _; } /** * @notice sets offchain reporting protocol configuration incl. participating oracles * @param _signers addresses with which oracles sign the reports * @param _transmitters addresses oracles use to transmit the reports * @param _threshold number of faulty oracles the system can tolerate * @param _encodedConfigVersion version number for offchainEncoding schema * @param _encoded encoded off-chain oracle configuration */ function setConfig( address[] calldata _signers, address[] calldata _transmitters, uint8 _threshold, uint64 _encodedConfigVersion, bytes calldata _encoded ) external checkConfigValid(_signers.length, _transmitters.length, _threshold) onlyOwner() { while (s_signers.length != 0) { // remove any old signer/transmitter addresses uint lastIdx = s_signers.length - 1; address signer = s_signers[lastIdx]; address transmitter = s_transmitters[lastIdx]; payOracle(transmitter); delete s_oracles[signer]; delete s_oracles[transmitter]; s_signers.pop(); s_transmitters.pop(); } for (uint i = 0; i < _signers.length; i++) { // add new signer/transmitter addresses require( s_oracles[_signers[i]].role == Role.Unset, "repeated signer address" ); s_oracles[_signers[i]] = Oracle(uint8(i), Role.Signer); require(s_payees[_transmitters[i]] != address(0), "payee must be set"); require( s_oracles[_transmitters[i]].role == Role.Unset, "repeated transmitter address" ); s_oracles[_transmitters[i]] = Oracle(uint8(i), Role.Transmitter); s_signers.push(_signers[i]); s_transmitters.push(_transmitters[i]); } s_hotVars.threshold = _threshold; uint32 previousConfigBlockNumber = s_latestConfigBlockNumber; s_latestConfigBlockNumber = uint32(block.number); s_configCount += 1; uint64 configCount = s_configCount; { s_hotVars.latestConfigDigest = configDigestFromConfigData( address(this), configCount, _signers, _transmitters, _threshold, _encodedConfigVersion, _encoded ); s_hotVars.latestEpochAndRound = 0; } emit ConfigSet( previousConfigBlockNumber, configCount, _signers, _transmitters, _threshold, _encodedConfigVersion, _encoded ); } function configDigestFromConfigData( address _contractAddress, uint64 _configCount, address[] calldata _signers, address[] calldata _transmitters, uint8 _threshold, uint64 _encodedConfigVersion, bytes calldata _encodedConfig ) internal pure returns (bytes16) { return bytes16(keccak256(abi.encode(_contractAddress, _configCount, _signers, _transmitters, _threshold, _encodedConfigVersion, _encodedConfig ))); } /** * @notice information about current offchain reporting protocol configuration * @return configCount ordinal number of current config, out of all configs applied to this contract so far * @return blockNumber block at which this config was set * @return configDigest domain-separation tag for current config (see configDigestFromConfigData) */ function latestConfigDetails() external view returns ( uint32 configCount, uint32 blockNumber, bytes16 configDigest ) { return (s_configCount, s_latestConfigBlockNumber, s_hotVars.latestConfigDigest); } /** * @return list of addresses permitted to transmit reports to this contract * @dev The list will match the order used to specify the transmitter during setConfig */ function transmitters() external view returns(address[] memory) { return s_transmitters; } /* * On-chain validation logc */ // Maximum gas the validation logic can use uint256 private constant VALIDATOR_GAS_LIMIT = 100000; // Contract containing the validation logic AggregatorValidatorInterface private s_validator; /** * @notice indicates that the address of the validator contract has been set * @param previous setting of the address prior to this event * @param current the new value for the address */ event ValidatorUpdated( address indexed previous, address indexed current ); /** * @notice address of the contract which does external data validation * @return validator address */ function validator() external view returns (AggregatorValidatorInterface) { return s_validator; } /** * @notice sets the address which does external data validation * @param _newValidator designates the address of the new validation contract */ function setValidator(address _newValidator) public onlyOwner() { address previous = address(s_validator); if (previous != _newValidator) { s_validator = AggregatorValidatorInterface(_newValidator); emit ValidatorUpdated(previous, _newValidator); } } function validateAnswer( uint32 _aggregatorRoundId, int256 _answer ) private { AggregatorValidatorInterface av = s_validator; // cache storage reads if (address(av) == address(0)) return; uint32 prevAggregatorRoundId = _aggregatorRoundId - 1; int256 prevAggregatorRoundAnswer = s_transmissions[prevAggregatorRoundId].answer; // We do not want the validator to ever prevent reporting, so we limit its // gas usage and catch any errors that may arise. try av.validate{gas: VALIDATOR_GAS_LIMIT}( prevAggregatorRoundId, prevAggregatorRoundAnswer, _aggregatorRoundId, _answer ) {} catch {} } /* * requestNewRound logic */ AccessControllerInterface internal s_requesterAccessController; /** * @notice emitted when a new requester access controller contract is set * @param old the address prior to the current setting * @param current the address of the new access controller contract */ event RequesterAccessControllerSet(AccessControllerInterface old, AccessControllerInterface current); /** * @notice emitted to immediately request a new round * @param requester the address of the requester * @param configDigest the latest transmission's configDigest * @param epoch the latest transmission's epoch * @param round the latest transmission's round */ event RoundRequested(address indexed requester, bytes16 configDigest, uint32 epoch, uint8 round); /** * @notice address of the requester access controller contract * @return requester access controller address */ function requesterAccessController() external view returns (AccessControllerInterface) { return s_requesterAccessController; } /** * @notice sets the requester access controller * @param _requesterAccessController designates the address of the new requester access controller */ function setRequesterAccessController(AccessControllerInterface _requesterAccessController) public onlyOwner() { AccessControllerInterface oldController = s_requesterAccessController; if (_requesterAccessController != oldController) { s_requesterAccessController = AccessControllerInterface(_requesterAccessController); emit RequesterAccessControllerSet(oldController, _requesterAccessController); } } /** * @notice immediately requests a new round * @return the aggregatorRoundId of the next round. Note: The report for this round may have been * transmitted (but not yet mined) *before* requestNewRound() was even called. There is *no* * guarantee of causality between the request and the report at aggregatorRoundId. */ function requestNewRound() external returns (uint80) { require(msg.sender == owner || s_requesterAccessController.hasAccess(msg.sender, msg.data), "Only owner&requester can call"); HotVars memory hotVars = s_hotVars; emit RoundRequested( msg.sender, hotVars.latestConfigDigest, uint32(s_hotVars.latestEpochAndRound >> 8), uint8(s_hotVars.latestEpochAndRound) ); return hotVars.latestAggregatorRoundId + 1; } /* * Transmission logic */ /** * @notice indicates that a new report was transmitted * @param aggregatorRoundId the round to which this report was assigned * @param answer median of the observations attached this report * @param transmitter address from which the report was transmitted * @param observations observations transmitted with this report * @param rawReportContext signature-replay-prevention domain-separation tag */ event NewTransmission( uint32 indexed aggregatorRoundId, int192 answer, address transmitter, int192[] observations, bytes observers, bytes32 rawReportContext ); // decodeReport is used to check that the solidity and go code are using the // same format. See TestOffchainAggregator.testDecodeReport and TestReportParsing function decodeReport(bytes memory _report) internal pure returns ( bytes32 rawReportContext, bytes32 rawObservers, int192[] memory observations ) { (rawReportContext, rawObservers, observations) = abi.decode(_report, (bytes32, bytes32, int192[])); } // Used to relieve stack pressure in transmit struct ReportData { HotVars hotVars; // Only read from storage once bytes observers; // ith element is the index of the ith observer int192[] observations; // ith element is the ith observation bytes vs; // jth element is the v component of the jth signature bytes32 rawReportContext; } /* * @notice details about the most recent report * @return configDigest domain separation tag for the latest report * @return epoch epoch in which the latest report was generated * @return round OCR round in which the latest report was generated * @return latestAnswer median value from latest report * @return latestTimestamp when the latest report was transmitted */ function latestTransmissionDetails() external view returns ( bytes16 configDigest, uint32 epoch, uint8 round, int192 latestAnswer, uint64 latestTimestamp ) { require(msg.sender == tx.origin, "Only callable by EOA"); return ( s_hotVars.latestConfigDigest, uint32(s_hotVars.latestEpochAndRound >> 8), uint8(s_hotVars.latestEpochAndRound), s_transmissions[s_hotVars.latestAggregatorRoundId].answer, s_transmissions[s_hotVars.latestAggregatorRoundId].timestamp ); } // The constant-length components of the msg.data sent to transmit. // See the "If we wanted to call sam" example on for example reasoning // https://solidity.readthedocs.io/en/v0.7.2/abi-spec.html uint16 private constant TRANSMIT_MSGDATA_CONSTANT_LENGTH_COMPONENT = 4 + // function selector 32 + // word containing start location of abiencoded _report value 32 + // word containing location start of abiencoded _rs value 32 + // word containing start location of abiencoded _ss value 32 + // _rawVs value 32 + // word containing length of _report 32 + // word containing length _rs 32 + // word containing length of _ss 0; // placeholder function expectedMsgDataLength( bytes calldata _report, bytes32[] calldata _rs, bytes32[] calldata _ss ) private pure returns (uint256 length) { // calldata will never be big enough to make this overflow return uint256(TRANSMIT_MSGDATA_CONSTANT_LENGTH_COMPONENT) + _report.length + // one byte pure entry in _report _rs.length * 32 + // 32 bytes per entry in _rs _ss.length * 32 + // 32 bytes per entry in _ss 0; // placeholder } /** * @notice transmit is called to post a new report to the contract * @param _report serialized report, which the signatures are signing. See parsing code below for format. The ith element of the observers component must be the index in s_signers of the address for the ith signature * @param _rs ith element is the R components of the ith signature on report. Must have at most maxNumOracles entries * @param _ss ith element is the S components of the ith signature on report. Must have at most maxNumOracles entries * @param _rawVs ith element is the the V component of the ith signature */ function transmit( // NOTE: If these parameters are changed, expectedMsgDataLength and/or // TRANSMIT_MSGDATA_CONSTANT_LENGTH_COMPONENT need to be changed accordingly bytes calldata _report, bytes32[] calldata _rs, bytes32[] calldata _ss, bytes32 _rawVs // signatures ) external { uint256 initialGas = gasleft(); // This line must come first // Make sure the transmit message-length matches the inputs. Otherwise, the // transmitter could append an arbitrarily long (up to gas-block limit) // string of 0 bytes, which we would reimburse at a rate of 16 gas/byte, but // which would only cost the transmitter 4 gas/byte. (Appendix G of the // yellow paper, p. 25, for G_txdatazero and EIP 2028 for G_txdatanonzero.) // This could amount to reimbursement profit of 36 million gas, given a 3MB // zero tail. require(msg.data.length == expectedMsgDataLength(_report, _rs, _ss), "transmit message too long"); ReportData memory r; // Relieves stack pressure { r.hotVars = s_hotVars; // cache read from storage bytes32 rawObservers; (r.rawReportContext, rawObservers, r.observations) = abi.decode( _report, (bytes32, bytes32, int192[]) ); // rawReportContext consists of: // 11-byte zero padding // 16-byte configDigest // 4-byte epoch // 1-byte round bytes16 configDigest = bytes16(r.rawReportContext << 88); require( r.hotVars.latestConfigDigest == configDigest, "configDigest mismatch" ); uint40 epochAndRound = uint40(uint256(r.rawReportContext)); // direct numerical comparison works here, because // // ((e,r) <= (e',r')) implies (epochAndRound <= epochAndRound') // // because alphabetic ordering implies e <= e', and if e = e', then r<=r', // so e*256+r <= e'*256+r', because r, r' < 256 require(r.hotVars.latestEpochAndRound < epochAndRound, "stale report"); require(_rs.length > r.hotVars.threshold, "not enough signatures"); require(_rs.length <= maxNumOracles, "too many signatures"); require(_ss.length == _rs.length, "signatures out of registration"); require(r.observations.length <= maxNumOracles, "num observations out of bounds"); require(r.observations.length > 2 * r.hotVars.threshold, "too few values to trust median"); // Copy signature parities in bytes32 _rawVs to bytes r.v r.vs = new bytes(_rs.length); for (uint8 i = 0; i < _rs.length; i++) { r.vs[i] = _rawVs[i]; } // Copy observer identities in bytes32 rawObservers to bytes r.observers r.observers = new bytes(r.observations.length); bool[maxNumOracles] memory seen; for (uint8 i = 0; i < r.observations.length; i++) { uint8 observerIdx = uint8(rawObservers[i]); require(!seen[observerIdx], "observer index repeated"); seen[observerIdx] = true; r.observers[i] = rawObservers[i]; } Oracle memory transmitter = s_oracles[msg.sender]; require( // Check that sender is authorized to report transmitter.role == Role.Transmitter && msg.sender == s_transmitters[transmitter.index], "unauthorized transmitter" ); // record epochAndRound here, so that we don't have to carry the local // variable in transmit. The change is reverted if something fails later. r.hotVars.latestEpochAndRound = epochAndRound; } { // Verify signatures attached to report bytes32 h = keccak256(_report); bool[maxNumOracles] memory signed; Oracle memory o; for (uint i = 0; i < _rs.length; i++) { address signer = ecrecover(h, uint8(r.vs[i])+27, _rs[i], _ss[i]); o = s_oracles[signer]; require(o.role == Role.Signer, "address not authorized to sign"); require(!signed[o.index], "non-unique signature"); signed[o.index] = true; } } { // Check the report contents, and record the result for (uint i = 0; i < r.observations.length - 1; i++) { bool inOrder = r.observations[i] <= r.observations[i+1]; require(inOrder, "observations not sorted"); } int192 median = r.observations[r.observations.length/2]; require(minAnswer <= median && median <= maxAnswer, "median is out of min-max range"); r.hotVars.latestAggregatorRoundId++; s_transmissions[r.hotVars.latestAggregatorRoundId] = Transmission(median, uint64(block.timestamp)); emit NewTransmission( r.hotVars.latestAggregatorRoundId, median, msg.sender, r.observations, r.observers, r.rawReportContext ); // Emit these for backwards compatability with offchain consumers // that only support legacy events emit NewRound( r.hotVars.latestAggregatorRoundId, address(0x0), // use zero address since we don't have anybody "starting" the round here block.timestamp ); emit AnswerUpdated( median, r.hotVars.latestAggregatorRoundId, block.timestamp ); validateAnswer(r.hotVars.latestAggregatorRoundId, median); } s_hotVars = r.hotVars; assert(initialGas < maxUint32); reimburseAndRewardOracles(uint32(initialGas), r.observers); } /* * v2 Aggregator interface */ /** * @notice median from the most recent report */ function latestAnswer() public override view virtual returns (int256) { return s_transmissions[s_hotVars.latestAggregatorRoundId].answer; } /** * @notice timestamp of block in which last report was transmitted */ function latestTimestamp() public override view virtual returns (uint256) { return s_transmissions[s_hotVars.latestAggregatorRoundId].timestamp; } /** * @notice Aggregator round (NOT OCR round) in which last report was transmitted */ function latestRound() public override view virtual returns (uint256) { return s_hotVars.latestAggregatorRoundId; } /** * @notice median of report from given aggregator round (NOT OCR round) * @param _roundId the aggregator round of the target report */ function getAnswer(uint256 _roundId) public override view virtual returns (int256) { if (_roundId > 0xFFFFFFFF) { return 0; } return s_transmissions[uint32(_roundId)].answer; } /** * @notice timestamp of block in which report from given aggregator round was transmitted * @param _roundId aggregator round (NOT OCR round) of target report */ function getTimestamp(uint256 _roundId) public override view virtual returns (uint256) { if (_roundId > 0xFFFFFFFF) { return 0; } return s_transmissions[uint32(_roundId)].timestamp; } /* * v3 Aggregator interface */ string constant private V3_NO_DATA_ERROR = "No data present"; /** * @return answers are stored in fixed-point format, with this many digits of precision */ uint8 immutable public override decimals; /** * @notice aggregator contract version */ uint256 constant public override version = 4; string internal s_description; /** * @notice human-readable description of observable this contract is reporting on */ function description() public override view virtual returns (string memory) { return s_description; } /** * @notice details for the given aggregator round * @param _roundId target aggregator round (NOT OCR round). Must fit in uint32 * @return roundId _roundId * @return answer median of report from given _roundId * @return startedAt timestamp of block in which report from given _roundId was transmitted * @return updatedAt timestamp of block in which report from given _roundId was transmitted * @return answeredInRound _roundId */ function getRoundData(uint80 _roundId) public override view virtual returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { require(_roundId <= 0xFFFFFFFF, V3_NO_DATA_ERROR); Transmission memory transmission = s_transmissions[uint32(_roundId)]; return ( _roundId, transmission.answer, transmission.timestamp, transmission.timestamp, _roundId ); } /** * @notice aggregator details for the most recently transmitted report * @return roundId aggregator round of latest report (NOT OCR round) * @return answer median of latest report * @return startedAt timestamp of block containing latest report * @return updatedAt timestamp of block containing latest report * @return answeredInRound aggregator round of latest report */ function latestRoundData() public override view virtual returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { roundId = s_hotVars.latestAggregatorRoundId; // Skipped for compatability with existing FluxAggregator in which latestRoundData never reverts. // require(roundId != 0, V3_NO_DATA_ERROR); Transmission memory transmission = s_transmissions[uint32(roundId)]; return ( roundId, transmission.answer, transmission.timestamp, transmission.timestamp, roundId ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface AccessControllerInterface { function hasAccess(address user, bytes calldata data) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface AggregatorValidatorInterface { function validate( uint256 previousRoundId, int256 previousAnswer, uint256 currentRoundId, int256 currentAnswer ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.1; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title The Owned contract * @notice A contract with helpers for basic contract ownership. */ contract Owned { address payable public owner; address private pendingOwner; event OwnershipTransferRequested( address indexed from, address indexed to ); event OwnershipTransferred( address indexed from, address indexed to ); constructor() { owner = msg.sender; } /** * @dev Allows an owner to begin transferring ownership to a new address, * pending. */ function transferOwnership(address _to) external onlyOwner() { pendingOwner = _to; emit OwnershipTransferRequested(owner, _to); } /** * @dev Allows an ownership transfer to be completed by the recipient. */ function acceptOwnership() external { require(msg.sender == pendingOwner, "Must be proposed owner"); address oldOwner = owner; owner = msg.sender; pendingOwner = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } /** * @dev Reverts if called by anyone other than the contract owner. */ modifier onlyOwner() { require(msg.sender == owner, "Only callable by owner"); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./AccessControllerInterface.sol"; import "./LinkTokenInterface.sol"; import "./Owned.sol"; /** * @notice tracks administration of oracle-reward and gas-reimbursement parameters. * @dev * If you read or change this, be sure to read or adjust the comments. They * track the units of the values under consideration, and are crucial to * the readability of the operations it specifies. * @notice * Trust Model: * Nothing in this contract prevents a billing admin from setting insane * values for the billing parameters in setBilling. Oracles * participating in this contract should regularly check that the * parameters make sense. Similarly, the outstanding obligations of this * contract to the oracles can exceed the funds held by the contract. * Oracles participating in this contract should regularly check that it * holds sufficient funds and stop interacting with it if funding runs * out. * This still leaves oracles with some risk due to TOCTOU issues. * However, since the sums involved are pretty small (Ethereum * transactions aren't that expensive in the end) and an oracle would * likely stop participating in a contract it repeatedly lost money on, * this risk is deemed acceptable. Oracles should also regularly * withdraw any funds in the contract to prevent issues where the * contract becomes underfunded at a later time, and different oracles * are competing for the left-over funds. * Finally, note that any change to the set of oracles or to the billing * parameters will trigger payout of all oracles first (using the old * parameters), a billing admin cannot take away funds that are already * marked for payment. */ contract OffchainAggregatorBilling is Owned { // Maximum number of oracles the offchain reporting protocol is designed for uint256 constant internal maxNumOracles = 31; // Parameters for oracle payments struct Billing { // Highest compensated gas price, in ETH-gwei uints uint32 maximumGasPrice; // If gas price is less (in ETH-gwei units), transmitter gets half the savings uint32 reasonableGasPrice; // Pay transmitter back this much LINK per unit eth spent on gas // (1e-6LINK/ETH units) uint32 microLinkPerEth; // Fixed LINK reward for each observer, in LINK-gwei units uint32 linkGweiPerObservation; // Fixed reward for transmitter, in linkGweiPerObservation units uint32 linkGweiPerTransmission; } Billing internal s_billing; /** * @return LINK token contract used for billing */ LinkTokenInterface immutable public LINK; AccessControllerInterface internal s_billingAccessController; // ith element is number of observation rewards due to ith process, plus one. // This is expected to saturate after an oracle has submitted 65,535 // observations, or about 65535/(3*24*20) = 45 days, given a transmission // every 3 minutes. // // This is always one greater than the actual value, so that when the value is // reset to zero, we don't end up with a zero value in storage (which would // result in a higher gas cost, the next time the value is incremented.) // Calculations using this variable need to take that offset into account. uint16[maxNumOracles] internal s_oracleObservationsCounts; // Addresses at which oracles want to receive payments, by transmitter address mapping (address /* transmitter */ => address /* payment address */) internal s_payees; // Payee addresses which must be approved by the owner mapping (address /* transmitter */ => address /* payment address */) internal s_proposedPayees; // LINK-wei-denominated reimbursements for gas used by transmitters. // // This is always one greater than the actual value, so that when the value is // reset to zero, we don't end up with a zero value in storage (which would // result in a higher gas cost, the next time the value is incremented.) // Calculations using this variable need to take that offset into account. // // Argument for overflow safety: // We have the following maximum intermediate values: // - 2**40 additions to this variable (epochAndRound is a uint40) // - 2**32 gas price in ethgwei/gas // - 1e9 ethwei/ethgwei // - 2**32 gas since the block gas limit is at ~20 million // - 2**32 (microlink/eth) // And we have 2**40 * 2**32 * 1e9 * 2**32 * 2**32 < 2**166 // (we also divide in some places, but that only makes the value smaller) // We can thus safely use uint256 intermediate values for the computation // updating this variable. uint256[maxNumOracles] internal s_gasReimbursementsLinkWei; // Used for s_oracles[a].role, where a is an address, to track the purpose // of the address, or to indicate that the address is unset. enum Role { // No oracle role has been set for address a Unset, // Signing address for the s_oracles[a].index'th oracle. I.e., report // signatures from this oracle should ecrecover back to address a. Signer, // Transmission address for the s_oracles[a].index'th oracle. I.e., if a // report is received by OffchainAggregator.transmit in which msg.sender is // a, it is attributed to the s_oracles[a].index'th oracle. Transmitter } struct Oracle { uint8 index; // Index of oracle in s_signers/s_transmitters Role role; // Role of the address which mapped to this struct } mapping (address /* signer OR transmitter address */ => Oracle) internal s_oracles; // s_signers contains the signing address of each oracle address[] internal s_signers; // s_transmitters contains the transmission address of each oracle, // i.e. the address the oracle actually sends transactions to the contract from address[] internal s_transmitters; uint256 constant private maxUint16 = (1 << 16) - 1; uint256 constant internal maxUint128 = (1 << 128) - 1; constructor( uint32 _maximumGasPrice, uint32 _reasonableGasPrice, uint32 _microLinkPerEth, uint32 _linkGweiPerObservation, uint32 _linkGweiPerTransmission, address _link, AccessControllerInterface _billingAccessController ) { setBillingInternal(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth, _linkGweiPerObservation, _linkGweiPerTransmission); setBillingAccessControllerInternal(_billingAccessController); LINK = LinkTokenInterface(_link); uint16[maxNumOracles] memory counts; // See s_oracleObservationsCounts docstring uint256[maxNumOracles] memory gas; // see s_gasReimbursementsLinkWei docstring for (uint8 i = 0; i < maxNumOracles; i++) { counts[i] = 1; gas[i] = 1; } s_oracleObservationsCounts = counts; s_gasReimbursementsLinkWei = gas; } /** * @notice emitted when billing parameters are set * @param maximumGasPrice highest gas price for which transmitter will be compensated * @param reasonableGasPrice transmitter will receive reward for gas prices under this value * @param microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units * @param linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units * @param linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units */ event BillingSet( uint32 maximumGasPrice, uint32 reasonableGasPrice, uint32 microLinkPerEth, uint32 linkGweiPerObservation, uint32 linkGweiPerTransmission ); function setBillingInternal( uint32 _maximumGasPrice, uint32 _reasonableGasPrice, uint32 _microLinkPerEth, uint32 _linkGweiPerObservation, uint32 _linkGweiPerTransmission ) internal { s_billing = Billing(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth, _linkGweiPerObservation, _linkGweiPerTransmission); emit BillingSet(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth, _linkGweiPerObservation, _linkGweiPerTransmission); } /** * @notice sets billing parameters * @param _maximumGasPrice highest gas price for which transmitter will be compensated * @param _reasonableGasPrice transmitter will receive reward for gas prices under this value * @param _microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units * @param _linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units * @param _linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units * @dev access control provided by billingAccessController */ function setBilling( uint32 _maximumGasPrice, uint32 _reasonableGasPrice, uint32 _microLinkPerEth, uint32 _linkGweiPerObservation, uint32 _linkGweiPerTransmission ) external { AccessControllerInterface access = s_billingAccessController; require(msg.sender == owner || access.hasAccess(msg.sender, msg.data), "Only owner&billingAdmin can call"); payOracles(); setBillingInternal(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth, _linkGweiPerObservation, _linkGweiPerTransmission); } /** * @notice gets billing parameters * @param maximumGasPrice highest gas price for which transmitter will be compensated * @param reasonableGasPrice transmitter will receive reward for gas prices under this value * @param microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units * @param linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units * @param linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units */ function getBilling() external view returns ( uint32 maximumGasPrice, uint32 reasonableGasPrice, uint32 microLinkPerEth, uint32 linkGweiPerObservation, uint32 linkGweiPerTransmission ) { Billing memory billing = s_billing; return ( billing.maximumGasPrice, billing.reasonableGasPrice, billing.microLinkPerEth, billing.linkGweiPerObservation, billing.linkGweiPerTransmission ); } /** * @notice emitted when a new access-control contract is set * @param old the address prior to the current setting * @param current the address of the new access-control contract */ event BillingAccessControllerSet(AccessControllerInterface old, AccessControllerInterface current); function setBillingAccessControllerInternal(AccessControllerInterface _billingAccessController) internal { AccessControllerInterface oldController = s_billingAccessController; if (_billingAccessController != oldController) { s_billingAccessController = _billingAccessController; emit BillingAccessControllerSet( oldController, _billingAccessController ); } } /** * @notice sets billingAccessController * @param _billingAccessController new billingAccessController contract address * @dev only owner can call this */ function setBillingAccessController(AccessControllerInterface _billingAccessController) external onlyOwner { setBillingAccessControllerInternal(_billingAccessController); } /** * @notice gets billingAccessController * @return address of billingAccessController contract */ function billingAccessController() external view returns (AccessControllerInterface) { return s_billingAccessController; } /** * @notice withdraws an oracle's payment from the contract * @param _transmitter the transmitter address of the oracle * @dev must be called by oracle's payee address */ function withdrawPayment(address _transmitter) external { require(msg.sender == s_payees[_transmitter], "Only payee can withdraw"); payOracle(_transmitter); } /** * @notice query an oracle's payment amount * @param _transmitter the transmitter address of the oracle */ function owedPayment(address _transmitter) public view returns (uint256) { Oracle memory oracle = s_oracles[_transmitter]; if (oracle.role == Role.Unset) { return 0; } Billing memory billing = s_billing; uint256 linkWeiAmount = uint256(s_oracleObservationsCounts[oracle.index] - 1) * uint256(billing.linkGweiPerObservation) * (1 gwei); linkWeiAmount += s_gasReimbursementsLinkWei[oracle.index] - 1; return linkWeiAmount; } /** * @notice emitted when an oracle has been paid LINK * @param transmitter address from which the oracle sends reports to the transmit method * @param payee address to which the payment is sent * @param amount amount of LINK sent */ event OraclePaid(address transmitter, address payee, uint256 amount); // payOracle pays out _transmitter's balance to the corresponding payee, and zeros it out function payOracle(address _transmitter) internal { Oracle memory oracle = s_oracles[_transmitter]; uint256 linkWeiAmount = owedPayment(_transmitter); if (linkWeiAmount > 0) { address payee = s_payees[_transmitter]; // Poses no re-entrancy issues, because LINK.transfer does not yield // control flow. require(LINK.transfer(payee, linkWeiAmount), "insufficient funds"); s_oracleObservationsCounts[oracle.index] = 1; // "zero" the counts. see var's docstring s_gasReimbursementsLinkWei[oracle.index] = 1; // "zero" the counts. see var's docstring emit OraclePaid(_transmitter, payee, linkWeiAmount); } } // payOracles pays out all transmitters, and zeros out their balances. // // It's much more gas-efficient to do this as a single operation, to avoid // hitting storage too much. function payOracles() internal { Billing memory billing = s_billing; uint16[maxNumOracles] memory observationsCounts = s_oracleObservationsCounts; uint256[maxNumOracles] memory gasReimbursementsLinkWei = s_gasReimbursementsLinkWei; address[] memory transmitters = s_transmitters; for (uint transmitteridx = 0; transmitteridx < transmitters.length; transmitteridx++) { uint256 reimbursementAmountLinkWei = gasReimbursementsLinkWei[transmitteridx] - 1; uint256 obsCount = observationsCounts[transmitteridx] - 1; uint256 linkWeiAmount = obsCount * uint256(billing.linkGweiPerObservation) * (1 gwei) + reimbursementAmountLinkWei; if (linkWeiAmount > 0) { address payee = s_payees[transmitters[transmitteridx]]; // Poses no re-entrancy issues, because LINK.transfer does not yield // control flow. require(LINK.transfer(payee, linkWeiAmount), "insufficient funds"); observationsCounts[transmitteridx] = 1; // "zero" the counts. gasReimbursementsLinkWei[transmitteridx] = 1; // "zero" the counts. emit OraclePaid(transmitters[transmitteridx], payee, linkWeiAmount); } } // "Zero" the accounting storage variables s_oracleObservationsCounts = observationsCounts; s_gasReimbursementsLinkWei = gasReimbursementsLinkWei; } function oracleRewards( bytes memory observers, uint16[maxNumOracles] memory observations ) internal pure returns (uint16[maxNumOracles] memory) { // reward each observer-participant with the observer reward for (uint obsIdx = 0; obsIdx < observers.length; obsIdx++) { uint8 observer = uint8(observers[obsIdx]); observations[observer] = saturatingAddUint16(observations[observer], 1); } return observations; } // This value needs to change if maxNumOracles is increased, or the accounting // calculations at the bottom of reimburseAndRewardOracles change. // // To recalculate it, run the profiler as described in // ../../profile/README.md, and add up the gas-usage values reported for the // lines in reimburseAndRewardOracles following the "gasLeft = gasleft()" // line. E.g., you will see output like this: // // 7 uint256 gasLeft = gasleft(); // 29 uint256 gasCostEthWei = transmitterGasCostEthWei( // 9 uint256(initialGas), // 3 gasPrice, // 3 callDataGasCost, // 3 gasLeft // . // . // . // 59 uint256 gasCostLinkWei = (gasCostEthWei * billing.microLinkPerEth)/ 1e6; // . // . // . // 5047 s_gasReimbursementsLinkWei[txOracle.index] = // 856 s_gasReimbursementsLinkWei[txOracle.index] + gasCostLinkWei + // 26 uint256(billing.linkGweiPerTransmission) * (1 gwei); // // If those were the only lines to be accounted for, you would add up // 29+9+3+3+3+59+5047+856+26=6035. uint256 internal constant accountingGasCost = 6035; // Uncomment the following declaration to compute the remaining gas cost after // above gasleft(). (This must exist in a base class to OffchainAggregator, so // it can't go in TestOffchainAggregator.) // // uint256 public gasUsedInAccounting; // Gas price at which the transmitter should be reimbursed, in ETH-gwei/gas function impliedGasPrice( uint256 txGasPrice, // ETH-gwei/gas units uint256 reasonableGasPrice, // ETH-gwei/gas units uint256 maximumGasPrice // ETH-gwei/gas units ) internal pure returns (uint256) { // Reward the transmitter for choosing an efficient gas price: if they manage // to come in lower than considered reasonable, give them half the savings. // // The following calculations are all in units of gwei/gas, i.e. 1e-9ETH/gas uint256 gasPrice = txGasPrice; if (txGasPrice < reasonableGasPrice) { // Give transmitter half the savings for coming in under the reasonable gas price gasPrice += (reasonableGasPrice - txGasPrice) / 2; } // Don't reimburse a gas price higher than maximumGasPrice return min(gasPrice, maximumGasPrice); } // gas reimbursement due the transmitter, in ETH-wei // // If this function is changed, accountingGasCost needs to change, too. See // its docstring function transmitterGasCostEthWei( uint256 initialGas, uint256 gasPrice, // ETH-gwei/gas units uint256 callDataCost, // gas units uint256 gasLeft ) internal pure returns (uint128 gasCostEthWei) { require(initialGas >= gasLeft, "gasLeft cannot exceed initialGas"); uint256 gasUsed = // gas units initialGas - gasLeft + // observed gas usage callDataCost + accountingGasCost; // estimated gas usage // gasUsed is in gas units, gasPrice is in ETH-gwei/gas units; convert to ETH-wei uint256 fullGasCostEthWei = gasUsed * gasPrice * (1 gwei); assert(fullGasCostEthWei < maxUint128); // the entire ETH supply fits in a uint128... return uint128(fullGasCostEthWei); } /** * @notice withdraw any available funds left in the contract, up to _amount, after accounting for the funds due to participants in past reports * @param _recipient address to send funds to * @param _amount maximum amount to withdraw, denominated in LINK-wei. * @dev access control provided by billingAccessController */ function withdrawFunds(address _recipient, uint256 _amount) external { require(msg.sender == owner || s_billingAccessController.hasAccess(msg.sender, msg.data), "Only owner&billingAdmin can call"); uint256 linkDue = totalLINKDue(); uint256 linkBalance = LINK.balanceOf(address(this)); require(linkBalance >= linkDue, "insufficient balance"); require(LINK.transfer(_recipient, min(linkBalance - linkDue, _amount)), "insufficient funds"); } // Total LINK due to participants in past reports. function totalLINKDue() internal view returns (uint256 linkDue) { // Argument for overflow safety: We do all computations in // uint256s. The inputs to linkDue are: // - the <= 31 observation rewards each of which has less than // 64 bits (32 bits for billing.linkGweiPerObservation, 32 bits // for wei/gwei conversion). Hence 69 bits are sufficient for this part. // - the <= 31 gas reimbursements, each of which consists of at most 166 // bits (see s_gasReimbursementsLinkWei docstring). Hence 171 bits are // sufficient for this part // In total, 172 bits are enough. uint16[maxNumOracles] memory observationCounts = s_oracleObservationsCounts; for (uint i = 0; i < maxNumOracles; i++) { linkDue += observationCounts[i] - 1; // Stored value is one greater than actual value } Billing memory billing = s_billing; // Convert linkGweiPerObservation to uint256, or this overflows! linkDue *= uint256(billing.linkGweiPerObservation) * (1 gwei); address[] memory transmitters = s_transmitters; uint256[maxNumOracles] memory gasReimbursementsLinkWei = s_gasReimbursementsLinkWei; for (uint i = 0; i < transmitters.length; i++) { linkDue += uint256(gasReimbursementsLinkWei[i]-1); // Stored value is one greater than actual value } } /** * @notice allows oracles to check that sufficient LINK balance is available * @return availableBalance LINK available on this contract, after accounting for outstanding obligations. can become negative */ function linkAvailableForPayment() external view returns (int256 availableBalance) { // there are at most one billion LINK, so this cast is safe int256 balance = int256(LINK.balanceOf(address(this))); // according to the argument in the definition of totalLINKDue, // totalLINKDue is never greater than 2**172, so this cast is safe int256 due = int256(totalLINKDue()); // safe from overflow according to above sizes return int256(balance) - int256(due); } /** * @notice number of observations oracle is due to be reimbursed for * @param _signerOrTransmitter address used by oracle for signing or transmitting reports */ function oracleObservationCount(address _signerOrTransmitter) external view returns (uint16) { Oracle memory oracle = s_oracles[_signerOrTransmitter]; if (oracle.role == Role.Unset) { return 0; } return s_oracleObservationsCounts[oracle.index] - 1; } function reimburseAndRewardOracles( uint32 initialGas, bytes memory observers ) internal { Oracle memory txOracle = s_oracles[msg.sender]; Billing memory billing = s_billing; // Reward oracles for providing observations. Oracles are not rewarded // for providing signatures, because signing is essentially free. s_oracleObservationsCounts = oracleRewards(observers, s_oracleObservationsCounts); // Reimburse transmitter of the report for gas usage require(txOracle.role == Role.Transmitter, "sent by undesignated transmitter" ); uint256 gasPrice = impliedGasPrice( tx.gasprice / (1 gwei), // convert to ETH-gwei units billing.reasonableGasPrice, billing.maximumGasPrice ); // The following is only an upper bound, as it ignores the cheaper cost for // 0 bytes. Safe from overflow, because calldata just isn't that long. uint256 callDataGasCost = 16 * msg.data.length; // If any changes are made to subsequent calculations, accountingGasCost // needs to change, too. uint256 gasLeft = gasleft(); uint256 gasCostEthWei = transmitterGasCostEthWei( uint256(initialGas), gasPrice, callDataGasCost, gasLeft ); // microLinkPerEth is 1e-6LINK/ETH units, gasCostEthWei is 1e-18ETH units // (ETH-wei), product is 1e-24LINK-wei units, dividing by 1e6 gives // 1e-18LINK units, i.e. LINK-wei units // Safe from over/underflow, since all components are non-negative, // gasCostEthWei will always fit into uint128 and microLinkPerEth is a // uint32 (128+32 < 256!). uint256 gasCostLinkWei = (gasCostEthWei * billing.microLinkPerEth)/ 1e6; // Safe from overflow, because gasCostLinkWei < 2**160 and // billing.linkGweiPerTransmission * (1 gwei) < 2**64 and we increment // s_gasReimbursementsLinkWei[txOracle.index] at most 2**40 times. s_gasReimbursementsLinkWei[txOracle.index] = s_gasReimbursementsLinkWei[txOracle.index] + gasCostLinkWei + uint256(billing.linkGweiPerTransmission) * (1 gwei); // convert from linkGwei to linkWei // Uncomment next line to compute the remaining gas cost after above gasleft(). // See OffchainAggregatorBilling.accountingGasCost docstring for more information. // // gasUsedInAccounting = gasLeft - gasleft(); } /* * Payee management */ /** * @notice emitted when a transfer of an oracle's payee address has been initiated * @param transmitter address from which the oracle sends reports to the transmit method * @param current the payeee address for the oracle, prior to this setting * @param proposed the proposed new payee address for the oracle */ event PayeeshipTransferRequested( address indexed transmitter, address indexed current, address indexed proposed ); /** * @notice emitted when a transfer of an oracle's payee address has been completed * @param transmitter address from which the oracle sends reports to the transmit method * @param current the payeee address for the oracle, prior to this setting */ event PayeeshipTransferred( address indexed transmitter, address indexed previous, address indexed current ); /** * @notice sets the payees for transmitting addresses * @param _transmitters addresses oracles use to transmit the reports * @param _payees addresses of payees corresponding to list of transmitters * @dev must be called by owner * @dev cannot be used to change payee addresses, only to initially populate them */ function setPayees( address[] calldata _transmitters, address[] calldata _payees ) external onlyOwner() { require(_transmitters.length == _payees.length, "transmitters.size != payees.size"); for (uint i = 0; i < _transmitters.length; i++) { address transmitter = _transmitters[i]; address payee = _payees[i]; address currentPayee = s_payees[transmitter]; bool zeroedOut = currentPayee == address(0); require(zeroedOut || currentPayee == payee, "payee already set"); s_payees[transmitter] = payee; if (currentPayee != payee) { emit PayeeshipTransferred(transmitter, currentPayee, payee); } } } /** * @notice first step of payeeship transfer (safe transfer pattern) * @param _transmitter transmitter address of oracle whose payee is changing * @param _proposed new payee address * @dev can only be called by payee address */ function transferPayeeship( address _transmitter, address _proposed ) external { require(msg.sender == s_payees[_transmitter], "only current payee can update"); require(msg.sender != _proposed, "cannot transfer to self"); address previousProposed = s_proposedPayees[_transmitter]; s_proposedPayees[_transmitter] = _proposed; if (previousProposed != _proposed) { emit PayeeshipTransferRequested(_transmitter, msg.sender, _proposed); } } /** * @notice second step of payeeship transfer (safe transfer pattern) * @param _transmitter transmitter address of oracle whose payee is changing * @dev can only be called by proposed new payee address */ function acceptPayeeship( address _transmitter ) external { require(msg.sender == s_proposedPayees[_transmitter], "only proposed payees can accept"); address currentPayee = s_payees[_transmitter]; s_payees[_transmitter] = msg.sender; s_proposedPayees[_transmitter] = address(0); emit PayeeshipTransferred(_transmitter, currentPayee, msg.sender); } /* * Helper functions */ function saturatingAddUint16(uint16 _x, uint16 _y) internal pure returns (uint16) { return uint16(min(uint256(_x)+uint256(_y), maxUint16)); } function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } return b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.1; import "./SimpleWriteAccessController.sol"; /** * @title SimpleReadAccessController * @notice Gives access to: * - any externally owned account (note that offchain actors can always read * any contract storage regardless of onchain access control measures, so this * does not weaken the access control while improving usability) * - accounts explicitly added to an access list * @dev SimpleReadAccessController is not suitable for access controlling writes * since it grants any externally owned account access! See * SimpleWriteAccessController for that. */ contract SimpleReadAccessController is SimpleWriteAccessController { /** * @notice Returns the access of an address * @param _user The address to query */ function hasAccess( address _user, bytes memory _calldata ) public view virtual override returns (bool) { return super.hasAccess(_user, _calldata) || _user == tx.origin; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./Owned.sol"; import "./AccessControllerInterface.sol"; /** * @title SimpleWriteAccessController * @notice Gives access to accounts explicitly added to an access list by the * controller's owner. * @dev does not make any special permissions for externally, see * SimpleReadAccessController for that. */ contract SimpleWriteAccessController is AccessControllerInterface, Owned { bool public checkEnabled; mapping(address => bool) internal accessList; event AddedAccess(address user); event RemovedAccess(address user); event CheckAccessEnabled(); event CheckAccessDisabled(); constructor() { checkEnabled = true; } /** * @notice Returns the access of an address * @param _user The address to query */ function hasAccess( address _user, bytes memory ) public view virtual override returns (bool) { return accessList[_user] || !checkEnabled; } /** * @notice Adds an address to the access list * @param _user The address to add */ function addAccess(address _user) external onlyOwner() { addAccessInternal(_user); } function addAccessInternal(address _user) internal { if (!accessList[_user]) { accessList[_user] = true; emit AddedAccess(_user); } } /** * @notice Removes an address from the access list * @param _user The address to remove */ function removeAccess(address _user) external onlyOwner() { if (accessList[_user]) { accessList[_user] = false; emit RemovedAccess(_user); } } /** * @notice makes the access check enforced */ function enableAccessCheck() external onlyOwner() { if (!checkEnabled) { checkEnabled = true; emit CheckAccessEnabled(); } } /** * @notice makes the access check unenforced */ function disableAccessCheck() external onlyOwner() { if (checkEnabled) { checkEnabled = false; emit CheckAccessDisabled(); } } /** * @dev reverts if the caller does not have access */ modifier checkAccess() { require(hasAccess(msg.sender, msg.data), "No access"); _; } }
* @notice median from the most recent report/
{ return s_transmissions[s_hotVars.latestAggregatorRoundId].answer; emit NewRound( }
51,083
[ 1, 22410, 628, 326, 4486, 8399, 2605, 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, 288, 203, 565, 327, 272, 67, 2338, 7300, 63, 87, 67, 15224, 5555, 18, 13550, 17711, 11066, 548, 8009, 13490, 31, 203, 1377, 3626, 1166, 11066, 12, 203, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-03-13 */ // File: bveCVX.sol pragma solidity ^0.6.11; pragma experimental ABIEncoderV2; // File: AddressUpgradeable.sol /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity\'s `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: ICVXBribes.sol interface ICVXBribes { function getReward(address _account, address _token) external; function getRewards(address _account, address[] calldata _tokens) external; } // File: IController.sol interface IController { function withdraw(address, uint256) external; function strategies(address) external view returns (address); function balanceOf(address) external view returns (uint256); function earn(address, uint256) external; function want(address) external view returns (address); function rewards() external view returns (address); function vaults(address) external view returns (address); } // File: ICurvePool.sol interface ICurvePool { function exchange( int128 i, int128 j, uint256 _dx, uint256 _min_dy ) external returns (uint256); } // File: ICvxLocker.sol interface ICvxLocker { function maximumBoostPayment() external view returns (uint256); function lock( address _account, uint256 _amount, uint256 _spendRatio ) external; function getReward(address _account, bool _stake) external; //BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch function balanceOf(address _user) external view returns (uint256 amount); // total token balance of an account, including unlocked but not withdrawn tokens function lockedBalanceOf(address _user) external view returns (uint256 amount); // Withdraw/relock all currently locked tokens where the unlock time has passed function processExpiredLocks( bool _relock, uint256 _spendRatio, address _withdrawTo ) external; // Withdraw/relock all currently locked tokens where the unlock time has passed function processExpiredLocks(bool _relock) external; } // File: IDelegateRegistry.sol ///@dev Snapshot Delegate registry so we can delegate voting to XYZ interface IDelegateRegistry { function setDelegate(bytes32 id, address delegate) external; function delegation(address, bytes32) external returns (address); } // File: IERC20Upgradeable.sol /** * @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: ISettV4.sol interface ISettV4 { function deposit(uint256 _amount) external; function depositFor(address _recipient, uint256 _amount) external; function withdraw(uint256 _amount) external; function balance() external view returns (uint256); function getPricePerFullShare() external view returns (uint256); function balanceOf(address) external view returns (uint256); function totalSupply() external view returns (uint256); } // File: IStrategy.sol interface IStrategy { function want() external view returns (address); function deposit() external; // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address) external returns (uint256 balance); // Controller | Vault role - withdraw should always return to Vault function withdraw(uint256) external; // Controller | Vault role - withdraw should always return to Vault function withdrawAll() external returns (uint256); function balanceOf() external view returns (uint256); function getName() external pure returns (string memory); function setStrategist(address _strategist) external; function setWithdrawalFee(uint256 _withdrawalFee) external; function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external; function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external; function setGovernance(address _governance) external; function setController(address _controller) external; function tend() external; function harvest() external; } // File: IUniswapRouterV2.sol interface IUniswapRouterV2 { function factory() external view returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // File: IVotiumBribes.sol interface IVotiumBribes { struct claimParam { address token; uint256 index; uint256 amount; bytes32[] merkleProof; } function claimMulti(address account, claimParam[] calldata claims) external; function claim(address token, uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external; } // File: Initializable.sol /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can\'t have a constructor, it\'s common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require( _initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized" ); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // File: MathUpgradeable.sol /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2); } } // File: ReentrancyGuard.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 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: SafeMathUpgradeable.sol /** * @dev Wrappers over Solidity\'s arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it\'s recommended to use it always. */ library SafeMathUpgradeable { /** * @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: ContextUpgradeable.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer {} function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File: ReentrancyGuardUpgradeable.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]. */ 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: SafeERC20Upgradeable.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // \'safeIncreaseAllowance\' and \'safeDecreaseAllowance\' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity\'s return data size checking mechanism, since // we\'re implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File: SettAccessControl.sol /* Common base for permissioned roles throughout Sett ecosystem */ contract SettAccessControl is Initializable { address public governance; address public strategist; address public keeper; // ===== MODIFIERS ===== function _onlyGovernance() internal view { require(msg.sender == governance, "onlyGovernance"); } function _onlyGovernanceOrStrategist() internal view { require( msg.sender == strategist || msg.sender == governance, "onlyGovernanceOrStrategist" ); } function _onlyAuthorizedActors() internal view { require( msg.sender == keeper || msg.sender == governance, "onlyAuthorizedActors" ); } // ===== PERMISSIONED ACTIONS ===== /// @notice Change strategist address /// @notice Can only be changed by governance itself function setStrategist(address _strategist) external { _onlyGovernance(); strategist = _strategist; } /// @notice Change keeper address /// @notice Can only be changed by governance itself function setKeeper(address _keeper) external { _onlyGovernance(); keeper = _keeper; } /// @notice Change governance address /// @notice Can only be changed by governance itself function setGovernance(address _governance) public { _onlyGovernance(); governance = _governance; } uint256[50] private __gap; } // File: PausableUpgradeable.sol /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // File: BaseStrategy.sol /* ===== Badger Base Strategy ===== Common base class for all Sett strategies Changelog V1.1 - Verify amount unrolled from strategy positions on withdraw() is within a threshold relative to the requested amount as a sanity check - Add version number which is displayed with baseStrategyVersion(). If a strategy does not implement this function, it can be assumed to be 1.0 V1.2 - Remove idle want handling from base withdraw() function. This should be handled as the strategy sees fit in _withdrawSome() */ abstract contract BaseStrategy is PausableUpgradeable, SettAccessControl { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; event Withdraw(uint256 amount); event WithdrawAll(uint256 balance); event WithdrawOther(address token, uint256 amount); event SetStrategist(address strategist); event SetGovernance(address governance); event SetController(address controller); event SetWithdrawalFee(uint256 withdrawalFee); event SetPerformanceFeeStrategist(uint256 performanceFeeStrategist); event SetPerformanceFeeGovernance(uint256 performanceFeeGovernance); event Harvest(uint256 harvested, uint256 indexed blockNumber); event Tend(uint256 tended); address public want; // Want: Curve.fi renBTC/wBTC (crvRenWBTC) LP token uint256 public performanceFeeGovernance; uint256 public performanceFeeStrategist; uint256 public withdrawalFee; uint256 public constant MAX_FEE = 10000; address public constant uniswap = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap Dex address public controller; address public guardian; uint256 public withdrawalMaxDeviationThreshold; function __BaseStrategy_init( address _governance, address _strategist, address _controller, address _keeper, address _guardian ) public initializer whenNotPaused { __Pausable_init(); governance = _governance; strategist = _strategist; keeper = _keeper; controller = _controller; guardian = _guardian; withdrawalMaxDeviationThreshold = 50; } // ===== Modifiers ===== function _onlyController() internal view { require(msg.sender == controller, "onlyController"); } function _onlyAuthorizedActorsOrController() internal view { require( msg.sender == keeper || msg.sender == governance || msg.sender == controller, "onlyAuthorizedActorsOrController" ); } function _onlyAuthorizedPausers() internal view { require( msg.sender == guardian || msg.sender == governance, "onlyPausers" ); } /// ===== View Functions ===== function baseStrategyVersion() public view returns (string memory) { return "1.2"; } /// @notice Get the balance of want held idle in the Strategy function balanceOfWant() public view returns (uint256) { return IERC20Upgradeable(want).balanceOf(address(this)); } /// @notice Get the total balance of want realized in the strategy, whether idle or active in Strategy positions. function balanceOf() public view virtual returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function isTendable() public view virtual returns (bool) { return false; } /// ===== Permissioned Actions: Governance ===== function setGuardian(address _guardian) external { _onlyGovernance(); guardian = _guardian; } function setWithdrawalFee(uint256 _withdrawalFee) external { _onlyGovernance(); require( _withdrawalFee <= MAX_FEE, "base-strategy/excessive-withdrawal-fee" ); withdrawalFee = _withdrawalFee; } function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external { _onlyGovernance(); require( _performanceFeeStrategist <= MAX_FEE, "base-strategy/excessive-strategist-performance-fee" ); performanceFeeStrategist = _performanceFeeStrategist; } function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external { _onlyGovernance(); require( _performanceFeeGovernance <= MAX_FEE, "base-strategy/excessive-governance-performance-fee" ); performanceFeeGovernance = _performanceFeeGovernance; } function setController(address _controller) external { _onlyGovernance(); controller = _controller; } function setWithdrawalMaxDeviationThreshold(uint256 _threshold) external { _onlyGovernance(); require( _threshold <= MAX_FEE, "base-strategy/excessive-max-deviation-threshold" ); withdrawalMaxDeviationThreshold = _threshold; } function deposit() public virtual whenNotPaused { _onlyAuthorizedActorsOrController(); uint256 _want = IERC20Upgradeable(want).balanceOf(address(this)); if (_want > 0) { _deposit(_want); } _postDeposit(); } // ===== Permissioned Actions: Controller ===== /// @notice Controller-only function to Withdraw partial funds, normally used with a vault withdrawal function withdrawAll() external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _withdrawAll(); _transferToVault(IERC20Upgradeable(want).balanceOf(address(this))); } /// @notice Withdraw partial funds from the strategy, unrolling from strategy positions as necessary /// @notice Processes withdrawal fee if present /// @dev If it fails to recover sufficient funds (defined by withdrawalMaxDeviationThreshold), the withdrawal should fail so that this unexpected behavior can be investigated function withdraw(uint256 _amount) external virtual whenNotPaused { _onlyController(); // Withdraw from strategy positions, typically taking from any idle want first. _withdrawSome(_amount); uint256 _postWithdraw = IERC20Upgradeable(want).balanceOf(address(this)); // Sanity check: Ensure we were able to retrieve sufficent want from strategy positions // If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold if (_postWithdraw < _amount) { uint256 diff = _diff(_amount, _postWithdraw); // Require that difference between expected and actual values is less than the deviation threshold percentage require( diff <= _amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE), "base-strategy/withdraw-exceed-max-deviation-threshold" ); } // Return the amount actually withdrawn if less than amount requested uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount); // Process withdrawal fee uint256 _fee = _processWithdrawalFee(_toWithdraw); // Transfer remaining to Vault to handle withdrawal _transferToVault(_toWithdraw.sub(_fee)); } // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address _asset) external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _onlyNotProtectedTokens(_asset); balance = IERC20Upgradeable(_asset).balanceOf(address(this)); IERC20Upgradeable(_asset).safeTransfer(controller, balance); } /// ===== Permissioned Actions: Authoized Contract Pausers ===== function pause() external { _onlyAuthorizedPausers(); _pause(); } function unpause() external { _onlyGovernance(); _unpause(); } /// ===== Internal Helper Functions ===== /// @notice If withdrawal fee is active, take the appropriate amount from the given value and transfer to rewards recipient /// @return The withdrawal fee that was taken function _processWithdrawalFee(uint256 _amount) internal returns (uint256) { if (withdrawalFee == 0) { return 0; } uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE); IERC20Upgradeable(want).safeTransfer( IController(controller).rewards(), fee ); return fee; } /// @dev Helper function to process an arbitrary fee /// @dev If the fee is active, transfers a given portion in basis points of the specified value to the recipient /// @return The fee that was taken function _processFee( address token, uint256 amount, uint256 feeBps, address recipient ) internal returns (uint256) { if (feeBps == 0) { return 0; } uint256 fee = amount.mul(feeBps).div(MAX_FEE); IERC20Upgradeable(token).safeTransfer(recipient, fee); return fee; } /// @dev Reset approval and approve exact amount function _safeApproveHelper( address token, address recipient, uint256 amount ) internal { IERC20Upgradeable(token).safeApprove(recipient, 0); IERC20Upgradeable(token).safeApprove(recipient, amount); } function _transferToVault(uint256 _amount) internal { address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don\'t burn the funds IERC20Upgradeable(want).safeTransfer(_vault, _amount); } /// @notice Swap specified balance of given token on Uniswap with given path function _swap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForTokens( balance, 0, path, address(this), now ); } function _swapEthIn(uint256 balance, address[] memory path) internal { IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}( 0, path, address(this), now ); } function _swapEthOut( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForETH( balance, 0, path, address(this), now ); } /// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible function _add_max_liquidity_uniswap(address token0, address token1) internal virtual { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this)); _safeApproveHelper(token0, uniswap, _token0Balance); _safeApproveHelper(token1, uniswap, _token1Balance); IUniswapRouterV2(uniswap).addLiquidity( token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp ); } /// @notice Utility function to diff two numbers, expects higher value in first position function _diff(uint256 a, uint256 b) internal pure returns (uint256) { require(a >= b, "diff/expected-higher-number-in-first-position"); return a.sub(b); } // ===== Abstract Functions: To be implemented by specific Strategies ===== /// @dev Internal deposit logic to be implemented by Stratgies function _deposit(uint256 _amount) internal virtual; function _postDeposit() internal virtual { //no-op by default } /// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther() function _onlyNotProtectedTokens(address _asset) internal virtual; function getProtectedTokens() external view virtual returns (address[] memory); /// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible function _withdrawAll() internal virtual; /// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible. /// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this function _withdrawSome(uint256 _amount) internal virtual returns (uint256); /// @dev Realize returns from positions /// @dev Returns can be reinvested into positions, or distributed in another fashion /// @dev Performance fees should also be implemented in this function /// @dev Override function stub is removed as each strategy can have it\'s own return signature for STATICCALL // function harvest() external virtual; /// @dev User-friendly name for this strategy for purposes of convenient reading function getName() external pure virtual returns (string memory); /// @dev Balance of want currently held in strategy positions function balanceOfPool() public view virtual returns (uint256); uint256[49] private __gap; } // File: MyStrategy.sol /** * CHANGELOG * V1.0 Initial Release, can lock * V1.1 Update to handle rewards which are sent to a multisig * V1.2 Update to emit badger, all other rewards are sent to multisig * V1.3 Updated Address to claim CVX Rewards * V1.4 Updated Claiming mechanism to allow claiming any token (using difference in balances) * V1.5 Unlocks are permissioneless, added Chainlink Keepeers integration * V1.6 New Locker, work towards fully permissioneless claiming // Protected Launch */ contract MyStrategy is BaseStrategy, ReentrancyGuardUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; uint256 public constant MAX_BPS = 10_000; // address public want // Inherited from BaseStrategy, the token the strategy wants, swaps into and tries to grow address public lpComponent; // Token we provide liquidity with address public reward; // Token we farm and swap to want / lpComponent address public constant BADGER_TREE = 0x660802Fc641b154aBA66a62137e71f331B6d787A; IDelegateRegistry public constant SNAPSHOT = IDelegateRegistry(0x469788fE6E9E9681C6ebF3bF78e7Fd26Fc015446); // The initial DELEGATE for the strategy // NOTE we can change it by using manualSetDelegate below address public constant DELEGATE = 0x14F83fF95D4Ec5E8812DDf42DA1232b0ba1015e6; bytes32 public constant DELEGATED_SPACE = 0x6376782e65746800000000000000000000000000000000000000000000000000; ISettV4 public constant CVXCRV_VAULT = ISettV4(0x2B5455aac8d64C14786c3a29858E43b5945819C0); // NOTE: Locker V2 ICvxLocker public constant LOCKER = ICvxLocker(0x72a19342e8F1838460eBFCCEf09F6585e32db86E); ICVXBribes public constant CVX_EXTRA_REWARDS = ICVXBribes(0xDecc7d761496d30F30b92Bdf764fb8803c79360D); IVotiumBribes public constant VOTIUM_BRIBE_CLAIMER = IVotiumBribes(0x378Ba9B73309bE80BF4C2c027aAD799766a7ED5A); // We hardcode, an upgrade is required to change this as it\'s a meaningful change address public constant BRIBES_RECEIVER = 0x6F76C6A1059093E21D8B1C13C4e20D8335e2909F; // We emit badger through the tree to the vault holders address public constant BADGER = 0x3472A5A71965499acd81997a54BBA8D852C6E53d; bool public withdrawalSafetyCheck = false; bool public harvestOnRebalance = false; // If nothing is unlocked, processExpiredLocks will revert bool public processLocksOnReinvest = false; bool public processLocksOnRebalance = false; // Used to signal to the Badger Tree that rewards where sent to it event TreeDistribution( address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); event RewardsCollected( address token, uint256 amount ); event PerformanceFeeGovernance( address indexed destination, address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); event PerformanceFeeStrategist( address indexed destination, address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); function initialize( address _governance, address _strategist, address _controller, address _keeper, address _guardian, address[3] memory _wantConfig, uint256[3] memory _feeConfig ) public initializer { __BaseStrategy_init( _governance, _strategist, _controller, _keeper, _guardian ); __ReentrancyGuard_init(); /// @dev Add config here want = _wantConfig[0]; lpComponent = _wantConfig[1]; reward = _wantConfig[2]; performanceFeeGovernance = _feeConfig[0]; performanceFeeStrategist = _feeConfig[1]; withdrawalFee = _feeConfig[2]; IERC20Upgradeable(reward).safeApprove(address(CVXCRV_VAULT), type(uint256).max); /// @dev do one off approvals here // Permissions for Locker IERC20Upgradeable(want).safeApprove(address(LOCKER), type(uint256).max); // Delegate voting to DELEGATE SNAPSHOT.setDelegate(DELEGATED_SPACE, DELEGATE); } /// ===== Extra Functions ===== /// @dev Change Delegation to another address function manualSetDelegate(address delegate) external { _onlyGovernance(); // Set delegate is enough as it will clear previous delegate automatically SNAPSHOT.setDelegate(DELEGATED_SPACE, delegate); } ///@dev Should we check if the amount requested is more than what we can return on withdrawal? function setWithdrawalSafetyCheck(bool newWithdrawalSafetyCheck) external { _onlyGovernance(); withdrawalSafetyCheck = newWithdrawalSafetyCheck; } ///@dev Should we harvest before doing manual rebalancing ///@notice you most likely want to skip harvest if everything is unlocked, or there\'s something wrong and you just want out function setHarvestOnRebalance(bool newHarvestOnRebalance) external { _onlyGovernance(); harvestOnRebalance = newHarvestOnRebalance; } ///@dev Should we processExpiredLocks during reinvest? function setProcessLocksOnReinvest(bool newProcessLocksOnReinvest) external { _onlyGovernance(); processLocksOnReinvest = newProcessLocksOnReinvest; } ///@dev Should we processExpiredLocks during manualRebalance? function setProcessLocksOnRebalance(bool newProcessLocksOnRebalance) external { _onlyGovernance(); processLocksOnRebalance = newProcessLocksOnRebalance; } // Claiming functions, wrote on 10th of March with goal of removing access controls on 10th June /// @dev Function to move rewards that are not protected /// @notice Only not protected, moves the whole amount using _handleRewardTransfer /// @notice because token paths are harcoded, this function is safe to be called by anyone function sweepRewardToken(address token) public nonReentrant { _onlyGovernanceOrStrategist(); _onlyNotProtectedTokens(token); uint256 toSend = IERC20Upgradeable(token).balanceOf(address(this)); _handleRewardTransfer(token, toSend); } /// @dev Bulk function for sweepRewardToken function sweepRewards(address[] calldata tokens) external { uint256 length = tokens.length; for(uint i = 0; i < length; i++){ sweepRewardToken(tokens[i]); } } /// @dev Skim away want to bring back ppfs to 1e18 /// @notice permissioneless function as all paths are hardcoded // In the future function skim() external nonReentrant { _onlyGovernanceOrStrategist(); // Just withdraw and deposit into more of the vault, and send it to tree uint256 beforeBalance = _getBalance(); uint256 totalSupply = _getTotalSupply(); // Take the excess amount that is throwing off peg // Works because both are in 1e18 uint256 excessAmount = beforeBalance.sub(totalSupply); if(excessAmount == 0) { return; } _sentTokenToBribesReceiver(want, excessAmount); // Check that ppfs is 1, back to peg // getPricePerFullShare == balance().mul(1e18).div(totalSupply()) require(_getBalance() == _getTotalSupply()); // Proof we skimmed only back to 1 ppfs } /// @dev given a token address, and convexAddress claim that as reward from CVX Extra Rewards /// @notice funds are transfered to the hardcoded address BRIBES_RECEIVER function claimBribeFromConvex (ICVXBribes convexAddress, address token) external nonReentrant { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); uint256 beforePricePerFullShare = _getPricePerFullShare(); uint256 beforeBalance = IERC20Upgradeable(token).balanceOf(address(this)); // Claim reward for token convexAddress.getReward(address(this), token); uint256 afterBalance = IERC20Upgradeable(token).balanceOf(address(this)); _handleRewardTransfer(token, afterBalance.sub(beforeBalance)); require(beforeVaultBalance == _getBalance(), "Balance can\'t change"); require(beforePricePerFullShare == _getPricePerFullShare(), "Ppfs can\'t change"); } /// @dev Given the ExtraRewards address and a list of tokens, claims and processes them /// @notice permissioneless function as all paths are hardcoded // In the future /// @notice allows claiming any token as it uses the difference in balance function claimBribesFromConvex(ICVXBribes convexAddress, address[] memory tokens) external nonReentrant { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); uint256 beforePricePerFullShare = _getPricePerFullShare(); // Also checks balance diff uint256 length = tokens.length; uint256[] memory beforeBalance = new uint256[](length); for(uint i = 0; i < length; i++){ beforeBalance[i] = IERC20Upgradeable(tokens[i]).balanceOf(address(this)); } // Claim reward for tokens convexAddress.getRewards(address(this), tokens); // Send reward to Multisig for(uint x = 0; x < length; x++){ _handleRewardTransfer(tokens[x], IERC20Upgradeable(tokens[x]).balanceOf(address(this)).sub(beforeBalance[x])); } require(beforeVaultBalance == _getBalance(), "Balance can\'t change"); require(beforePricePerFullShare == _getPricePerFullShare(), "Ppfs can\'t change"); } /// @dev given the votium data and their tree address (available at: https://github.com/oo-00/Votium/tree/main/merkle) /// @dev allows claiming of rewards, badger is sent to tree function claimBribeFromVotium( IVotiumBribes votiumTree, address token, uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof ) external nonReentrant { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); uint256 beforePricePerFullShare = _getPricePerFullShare(); uint256 beforeBalance = IERC20Upgradeable(token).balanceOf(address(this)); votiumTree.claim(token, index, account, amount, merkleProof); uint256 afterBalance = IERC20Upgradeable(token).balanceOf(address(this)); _handleRewardTransfer(token, afterBalance.sub(beforeBalance)); require(beforeVaultBalance == _getBalance(), "Balance can\'t change"); require(beforePricePerFullShare == _getPricePerFullShare(), "Ppfs can\'t change"); } /// @dev given the votium data (available at: https://github.com/oo-00/Votium/tree/main/merkle) /// @dev allows claiming of multiple rewards rewards, badger is sent to tree /// @notice permissioneless function as all paths are hardcoded // In the future /// @notice allows claiming any token as it uses the difference in balance function claimBribesFromVotium( IVotiumBribes votiumTree, address account, address[] calldata tokens, uint256[] calldata indexes, uint256[] calldata amounts, bytes32[][] calldata merkleProofs ) external nonReentrant { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); uint256 beforePricePerFullShare = _getPricePerFullShare(); require(tokens.length == indexes.length && tokens.length == amounts.length && tokens.length == merkleProofs.length, "Length Mismatch"); // tokens.length = length, can\'t declare var as stack too deep uint256[] memory beforeBalance = new uint256[](tokens.length); for(uint i = 0; i < tokens.length; i++){ beforeBalance[i] = IERC20Upgradeable(tokens[i]).balanceOf(address(this)); } IVotiumBribes.claimParam[] memory request = new IVotiumBribes.claimParam[](tokens.length); for(uint x = 0; x < tokens.length; x++){ request[x] = IVotiumBribes.claimParam({ token: tokens[x], index: indexes[x], amount: amounts[x], merkleProof: merkleProofs[x] }); } votiumTree.claimMulti(account, request); for(uint i = 0; i < tokens.length; i++){ address token = tokens[i]; // Caching it allows it to compile else we hit stack too deep _handleRewardTransfer(token, IERC20Upgradeable(token).balanceOf(address(this)).sub(beforeBalance[i])); } require(beforeVaultBalance == _getBalance(), "Balance can\'t change"); require(beforePricePerFullShare == _getPricePerFullShare(), "Ppfs can\'t change"); } // END TRUSTLESS /// *** Handling of rewards *** function _handleRewardTransfer(address token, uint256 amount) internal { // NOTE: BADGER is emitted through the tree if (token == BADGER){ _sendBadgerToTree(amount); } else { // NOTE: All other tokens are sent to multisig _sentTokenToBribesReceiver(token, amount); } } /// @dev Send funds to the bribes receiver function _sentTokenToBribesReceiver(address token, uint256 amount) internal { IERC20Upgradeable(token).safeTransfer(BRIBES_RECEIVER, amount); emit RewardsCollected(token, amount); } /// @dev Send the BADGER token to the badgerTree function _sendBadgerToTree(uint256 amount) internal { IERC20Upgradeable(BADGER).safeTransfer(BADGER_TREE, amount); emit TreeDistribution(BADGER, amount, block.number, block.timestamp); } /// @dev Get the current Vault.balance /// @notice this is reflexive, a change in the strat will change the balance in the vault function _getBalance() internal returns (uint256) { ISettV4 vault = ISettV4(IController(controller).vaults(want)); return vault.balance(); } /// @dev Get the current Vault.totalSupply function _getTotalSupply() internal returns (uint256) { ISettV4 vault = ISettV4(IController(controller).vaults(want)); return vault.totalSupply(); } function _getPricePerFullShare() internal returns (uint256) { ISettV4 vault = ISettV4(IController(controller).vaults(want)); return vault.getPricePerFullShare(); } /// ===== View Functions ===== function getBoostPayment() public view returns(uint256){ // uint256 maximumBoostPayment = LOCKER.maximumBoostPayment(); // require(maximumBoostPayment <= 1500, "over max payment"); //max 15% return 0; // Unused at this stage, so for security reasons we just zero it } /// @dev Specify the name of the strategy function getName() external pure override returns (string memory) { return "veCVX Voting Strategy"; } /// @dev Specify the version of the Strategy, for upgrades function version() external pure returns (string memory) { return "1.6"; } /// @dev Balance of want currently held in strategy positions function balanceOfPool() public view override returns (uint256) { // Return the balance in locker return LOCKER.lockedBalanceOf(address(this)); } /// @dev Returns true if this strategy requires tending function isTendable() public view override returns (bool) { return false; } // @dev These are the tokens that cannot be moved except by the vault function getProtectedTokens() public view override returns (address[] memory) { address[] memory protectedTokens = new address[](3); protectedTokens[0] = want; protectedTokens[1] = lpComponent; // vlCVX protectedTokens[2] = reward; // cvxCRV // return protectedTokens; } /// ===== Internal Core Implementations ===== /// @dev security check to avoid moving tokens that would cause a rugpull, edit based on strat function _onlyNotProtectedTokens(address _asset) internal override { address[] memory protectedTokens = getProtectedTokens(); for (uint256 x = 0; x < protectedTokens.length; x++) { require( address(protectedTokens[x]) != _asset, "Asset is protected" ); } } /// @dev invest the amount of want /// @notice When this function is called, the controller has already sent want to this /// @notice Just get the current balance and then invest accordingly function _deposit(uint256 _amount) internal override { // Lock tokens for 16 weeks, send credit to strat, always use max boost cause why not? LOCKER.lock(address(this), _amount, getBoostPayment()); } /// @dev utility function to withdraw all CVX that we can from the lock function prepareWithdrawAll() external { manualProcessExpiredLocks(); } /// @dev utility function to withdraw everything for migration /// @dev NOTE: You cannot call this unless you have rebalanced to have only CVX left in the vault function _withdrawAll() internal override { //NOTE: This probably will always fail unless we have all tokens expired require( LOCKER.lockedBalanceOf(address(this)) == 0 && LOCKER.balanceOf(address(this)) == 0, "You have to wait for unlock or have to manually rebalance out of it" ); // Make sure to call prepareWithdrawAll before _withdrawAll } /// @dev withdraw the specified amount of want, liquidate from lpComponent to want, paying off any necessary debt for the conversion function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 max = balanceOfWant(); if(_amount > max){ // Try to unlock, as much as possible // @notice Reverts if no locks expired LOCKER.processExpiredLocks(false); max = balanceOfWant(); } if (withdrawalSafetyCheck) { require( max >= _amount.mul(9_980).div(MAX_BPS), "Withdrawal Safety Check" ); // 20 BP of slippage } if (_amount > max) { return max; } return _amount; } /// @dev Harvest from strategy mechanics, realizing increase in underlying position function harvest() public whenNotPaused returns (uint256) { _onlyAuthorizedActors(); uint256 _beforeReward = IERC20Upgradeable(reward).balanceOf(address(this)); // Get cvxCRV LOCKER.getReward(address(this), false); // Rewards Math uint256 earnedReward = IERC20Upgradeable(reward).balanceOf(address(this)).sub(_beforeReward); uint256 cvxCrvToGovernance = earnedReward.mul(performanceFeeGovernance).div(MAX_FEE); if(cvxCrvToGovernance > 0){ CVXCRV_VAULT.depositFor(IController(controller).rewards(), cvxCrvToGovernance); emit PerformanceFeeGovernance(IController(controller).rewards(), address(CVXCRV_VAULT), cvxCrvToGovernance, block.number, block.timestamp); } uint256 cvxCrvToStrategist = earnedReward.mul(performanceFeeStrategist).div(MAX_FEE); if(cvxCrvToStrategist > 0){ CVXCRV_VAULT.depositFor(strategist, cvxCrvToStrategist); emit PerformanceFeeStrategist(strategist, address(CVXCRV_VAULT), cvxCrvToStrategist, block.number, block.timestamp); } // Send rest of earned to tree //We send all rest to avoid dust and avoid protecting the token // We take difference of vault token to emit the event in shares rather than underlying uint256 cvxCRVInitialBalance = CVXCRV_VAULT.balanceOf(BADGER_TREE); uint256 cvxCrvToTree = IERC20Upgradeable(reward).balanceOf(address(this)); CVXCRV_VAULT.depositFor(BADGER_TREE, cvxCrvToTree); uint256 cvxCRVAfterBalance = CVXCRV_VAULT.balanceOf(BADGER_TREE); emit TreeDistribution(address(CVXCRV_VAULT), cvxCRVAfterBalance.sub(cvxCRVInitialBalance), block.number, block.timestamp); /// @dev Harvest event that every strategy MUST have, see BaseStrategy emit Harvest(earnedReward, block.number); /// @dev Harvest must return the amount of want increased return earnedReward; } /// @dev Rebalance, Compound or Pay off debt here function tend() external whenNotPaused { revert("no op"); // NOTE: For now tend is replaced by manualRebalance } /// MANUAL FUNCTIONS /// /// @dev manual function to reinvest all CVX that was locked function reinvest() external whenNotPaused returns (uint256) { _onlyGovernance(); if (processLocksOnReinvest) { // Withdraw all we can LOCKER.processExpiredLocks(false); } // Redeposit all into veCVX uint256 toDeposit = IERC20Upgradeable(want).balanceOf(address(this)); // Redeposit into veCVX _deposit(toDeposit); return toDeposit; } /// @dev process all locks, to redeem /// @notice No Access Control Checks, anyone can unlock an expired lock function manualProcessExpiredLocks() public whenNotPaused { // Unlock veCVX that is expired and redeem CVX back to this strat LOCKER.processExpiredLocks(false); } function checkUpkeep(bytes calldata checkData) external view returns (bool upkeepNeeded, bytes memory performData) { // We need to unlock funds if the lockedBalance (locked + unlocked) is greater than the balance (actively locked for this epoch) upkeepNeeded = LOCKER.lockedBalanceOf(address(this)) > LOCKER.balanceOf(address(this)); } /// @dev Function for ChainLink Keepers to automatically process expired locks function performUpkeep(bytes calldata performData) external { // Works like this because it reverts if lock is not expired LOCKER.processExpiredLocks(false); } /// @dev Send all available CVX to the Vault /// @notice you can do this so you can earn again (re-lock), or just to add to the redemption pool function manualSendCVXToVault() external whenNotPaused { _onlyGovernance(); uint256 cvxAmount = IERC20Upgradeable(want).balanceOf(address(this)); _transferToVault(cvxAmount); } /// @dev use the currently available CVX to lock /// @notice toLock = 0, lock nothing, deposit in CVX as much as you can /// @notice toLock = 10_000, lock everything (CVX) you have function manualRebalance(uint256 toLock) external whenNotPaused { _onlyGovernance(); require(toLock <= MAX_BPS, "Max is 100%"); if (processLocksOnRebalance) { // manualRebalance will revert if you have no expired locks LOCKER.processExpiredLocks(false); } if (harvestOnRebalance) { harvest(); } // Token that is highly liquid uint256 balanceOfWant = IERC20Upgradeable(want).balanceOf(address(this)); // Locked CVX in the locker uint256 balanceInLock = LOCKER.balanceOf(address(this)); uint256 totalCVXBalance = balanceOfWant.add(balanceInLock); // Amount we want to have in lock uint256 newLockAmount = totalCVXBalance.mul(toLock).div(MAX_BPS); // We can\'t unlock enough, no-op if (newLockAmount <= balanceInLock) { return; } // If we\'re continuing, then we are going to lock something uint256 cvxToLock = newLockAmount.sub(balanceInLock); // We only lock up to the available CVX uint256 maxCVX = IERC20Upgradeable(want).balanceOf(address(this)); if (cvxToLock > maxCVX) { // Just lock what we can LOCKER.lock(address(this), maxCVX, getBoostPayment()); } else { // Lock proper LOCKER.lock(address(this), cvxToLock, getBoostPayment()); } // If anything left, send to vault uint256 cvxLeft = IERC20Upgradeable(want).balanceOf(address(this)); if(cvxLeft > 0){ _transferToVault(cvxLeft); } } }
@notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther() @dev Internal logic for strategy migration. Should exit positions as efficiently as possible @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible. @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this @dev Realize returns from positions @dev Returns can be reinvested into positions, or distributed in another fashion @dev Performance fees should also be implemented in this function @dev Override function stub is removed as each strategy can have it\'s own return signature for STATICCALL function harvest() external virtual; @dev User-friendly name for this strategy for purposes of convenient reading @dev Balance of want currently held in strategy positions File: MyStrategy.sol* CHANGELOG V1.0 Initial Release, can lock V1.1 Update to handle rewards which are sent to a multisig V1.2 Update to emit badger, all other rewards are sent to multisig V1.3 Updated Address to claim CVX Rewards V1.4 Updated Claiming mechanism to allow claiming any token (using difference in balances) V1.5 Unlocks are permissioneless, added Chainlink Keepeers integration/ address public want Inherited from BaseStrategy, the token the strategy wants, swaps into and tries to grow The initial DELEGATE for the strategy NOTE we can change it by using manualSetDelegate below NOTE: Locker V2 We hardcode, an upgrade is required to change this as it\'s a meaningful change We emit badger through the tree to the vault holders If nothing is unlocked, processExpiredLocks will revert Used to signal to the Badger Tree that rewards where sent to it
contract MyStrategy is BaseStrategy, ReentrancyGuardUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; uint256 public constant MAX_BPS = 10_000; address public constant BADGER_TREE = 0x660802Fc641b154aBA66a62137e71f331B6d787A; IDelegateRegistry public constant SNAPSHOT = IDelegateRegistry(0x469788fE6E9E9681C6ebF3bF78e7Fd26Fc015446); address public constant DELEGATE = 0x14F83fF95D4Ec5E8812DDf42DA1232b0ba1015e6; bytes32 public constant DELEGATED_SPACE = 0x6376782e65746800000000000000000000000000000000000000000000000000; ISettV4 public constant CVXCRV_VAULT = ISettV4(0x2B5455aac8d64C14786c3a29858E43b5945819C0); ICvxLocker public constant LOCKER = ICvxLocker(0x72a19342e8F1838460eBFCCEf09F6585e32db86E); ICVXBribes public constant CVX_EXTRA_REWARDS = ICVXBribes(0xDecc7d761496d30F30b92Bdf764fb8803c79360D); IVotiumBribes public constant VOTIUM_BRIBE_CLAIMER = IVotiumBribes(0x378Ba9B73309bE80BF4C2c027aAD799766a7ED5A); address public constant BRIBES_RECEIVER = 0x6F76C6A1059093E21D8B1C13C4e20D8335e2909F; address public constant BADGER = 0x3472A5A71965499acd81997a54BBA8D852C6E53d; bool public withdrawalSafetyCheck = false; bool public harvestOnRebalance = false; bool public processLocksOnReinvest = false; bool public processLocksOnRebalance = false; event TreeDistribution( address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); event RewardsCollected( address token, uint256 amount ); event PerformanceFeeGovernance( address indexed destination, address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); event PerformanceFeeStrategist( address indexed destination, address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); function initialize( address _governance, address _strategist, address _controller, address _keeper, address _guardian, address[3] memory _wantConfig, uint256[3] memory _feeConfig function _onlyNotProtectedTokens(address _asset) internal virtual; function getProtectedTokens() external view virtual returns (address[] memory); function _withdrawAll() internal virtual; function _withdrawSome(uint256 _amount) internal virtual returns (uint256); function getName() external pure virtual returns (string memory); function balanceOfPool() public view virtual returns (uint256); uint256[49] private __gap; } ) public initializer { __BaseStrategy_init( _governance, _strategist, _controller, _keeper, _guardian ); __ReentrancyGuard_init(); want = _wantConfig[0]; lpComponent = _wantConfig[1]; reward = _wantConfig[2]; performanceFeeGovernance = _feeConfig[0]; performanceFeeStrategist = _feeConfig[1]; withdrawalFee = _feeConfig[2]; IERC20Upgradeable(reward).safeApprove(address(CVXCRV_VAULT), type(uint256).max); IERC20Upgradeable(want).safeApprove(address(LOCKER), type(uint256).max); SNAPSHOT.setDelegate(DELEGATED_SPACE, DELEGATE); } function manualSetDelegate(address delegate) external { _onlyGovernance(); SNAPSHOT.setDelegate(DELEGATED_SPACE, delegate); } function setWithdrawalSafetyCheck(bool newWithdrawalSafetyCheck) external { _onlyGovernance(); withdrawalSafetyCheck = newWithdrawalSafetyCheck; } function setHarvestOnRebalance(bool newHarvestOnRebalance) external { _onlyGovernance(); harvestOnRebalance = newHarvestOnRebalance; } function setProcessLocksOnReinvest(bool newProcessLocksOnReinvest) external { _onlyGovernance(); processLocksOnReinvest = newProcessLocksOnReinvest; } function setProcessLocksOnRebalance(bool newProcessLocksOnRebalance) external { _onlyGovernance(); processLocksOnRebalance = newProcessLocksOnRebalance; } function sweepRewardToken(address token) public nonReentrant { _onlyGovernanceOrStrategist(); _onlyNotProtectedTokens(token); uint256 toSend = IERC20Upgradeable(token).balanceOf(address(this)); _handleRewardTransfer(token, toSend); } function sweepRewards(address[] calldata tokens) external { uint256 length = tokens.length; for(uint i = 0; i < length; i++){ sweepRewardToken(tokens[i]); } } function sweepRewards(address[] calldata tokens) external { uint256 length = tokens.length; for(uint i = 0; i < length; i++){ sweepRewardToken(tokens[i]); } } function skim() external nonReentrant { _onlyGovernanceOrStrategist(); uint256 beforeBalance = _getBalance(); uint256 totalSupply = _getTotalSupply(); uint256 excessAmount = beforeBalance.sub(totalSupply); _sentTokenToBribesReceiver(want, excessAmount); } if(excessAmount == 0) { return; } function claimBribeFromConvex (ICVXBribes convexAddress, address token) external nonReentrant { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); uint256 beforePricePerFullShare = _getPricePerFullShare(); uint256 beforeBalance = IERC20Upgradeable(token).balanceOf(address(this)); convexAddress.getReward(address(this), token); uint256 afterBalance = IERC20Upgradeable(token).balanceOf(address(this)); _handleRewardTransfer(token, afterBalance.sub(beforeBalance)); require(beforeVaultBalance == _getBalance(), "Balance can\'t change"); require(beforePricePerFullShare == _getPricePerFullShare(), "Ppfs can\'t change"); } function claimBribesFromConvex(ICVXBribes convexAddress, address[] memory tokens) external nonReentrant { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); uint256 beforePricePerFullShare = _getPricePerFullShare(); uint256 length = tokens.length; uint256[] memory beforeBalance = new uint256[](length); for(uint i = 0; i < length; i++){ beforeBalance[i] = IERC20Upgradeable(tokens[i]).balanceOf(address(this)); } for(uint x = 0; x < length; x++){ _handleRewardTransfer(tokens[x], IERC20Upgradeable(tokens[x]).balanceOf(address(this)).sub(beforeBalance[x])); } require(beforeVaultBalance == _getBalance(), "Balance can\'t change"); require(beforePricePerFullShare == _getPricePerFullShare(), "Ppfs can\'t change"); } function claimBribesFromConvex(ICVXBribes convexAddress, address[] memory tokens) external nonReentrant { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); uint256 beforePricePerFullShare = _getPricePerFullShare(); uint256 length = tokens.length; uint256[] memory beforeBalance = new uint256[](length); for(uint i = 0; i < length; i++){ beforeBalance[i] = IERC20Upgradeable(tokens[i]).balanceOf(address(this)); } for(uint x = 0; x < length; x++){ _handleRewardTransfer(tokens[x], IERC20Upgradeable(tokens[x]).balanceOf(address(this)).sub(beforeBalance[x])); } require(beforeVaultBalance == _getBalance(), "Balance can\'t change"); require(beforePricePerFullShare == _getPricePerFullShare(), "Ppfs can\'t change"); } convexAddress.getRewards(address(this), tokens); function claimBribesFromConvex(ICVXBribes convexAddress, address[] memory tokens) external nonReentrant { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); uint256 beforePricePerFullShare = _getPricePerFullShare(); uint256 length = tokens.length; uint256[] memory beforeBalance = new uint256[](length); for(uint i = 0; i < length; i++){ beforeBalance[i] = IERC20Upgradeable(tokens[i]).balanceOf(address(this)); } for(uint x = 0; x < length; x++){ _handleRewardTransfer(tokens[x], IERC20Upgradeable(tokens[x]).balanceOf(address(this)).sub(beforeBalance[x])); } require(beforeVaultBalance == _getBalance(), "Balance can\'t change"); require(beforePricePerFullShare == _getPricePerFullShare(), "Ppfs can\'t change"); } function claimBribeFromVotium( IVotiumBribes votiumTree, address token, uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof ) external nonReentrant { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); uint256 beforePricePerFullShare = _getPricePerFullShare(); uint256 beforeBalance = IERC20Upgradeable(token).balanceOf(address(this)); votiumTree.claim(token, index, account, amount, merkleProof); uint256 afterBalance = IERC20Upgradeable(token).balanceOf(address(this)); _handleRewardTransfer(token, afterBalance.sub(beforeBalance)); require(beforeVaultBalance == _getBalance(), "Balance can\'t change"); require(beforePricePerFullShare == _getPricePerFullShare(), "Ppfs can\'t change"); } function claimBribesFromVotium( IVotiumBribes votiumTree, address account, address[] calldata tokens, uint256[] calldata indexes, uint256[] calldata amounts, bytes32[][] calldata merkleProofs ) external nonReentrant { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); uint256 beforePricePerFullShare = _getPricePerFullShare(); require(tokens.length == indexes.length && tokens.length == amounts.length && tokens.length == merkleProofs.length, "Length Mismatch"); uint256[] memory beforeBalance = new uint256[](tokens.length); for(uint i = 0; i < tokens.length; i++){ beforeBalance[i] = IERC20Upgradeable(tokens[i]).balanceOf(address(this)); } IVotiumBribes.claimParam[] memory request = new IVotiumBribes.claimParam[](tokens.length); for(uint x = 0; x < tokens.length; x++){ request[x] = IVotiumBribes.claimParam({ token: tokens[x], index: indexes[x], amount: amounts[x], merkleProof: merkleProofs[x] }); } votiumTree.claimMulti(account, request); for(uint i = 0; i < tokens.length; i++){ _handleRewardTransfer(token, IERC20Upgradeable(token).balanceOf(address(this)).sub(beforeBalance[i])); } require(beforeVaultBalance == _getBalance(), "Balance can\'t change"); require(beforePricePerFullShare == _getPricePerFullShare(), "Ppfs can\'t change"); } function claimBribesFromVotium( IVotiumBribes votiumTree, address account, address[] calldata tokens, uint256[] calldata indexes, uint256[] calldata amounts, bytes32[][] calldata merkleProofs ) external nonReentrant { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); uint256 beforePricePerFullShare = _getPricePerFullShare(); require(tokens.length == indexes.length && tokens.length == amounts.length && tokens.length == merkleProofs.length, "Length Mismatch"); uint256[] memory beforeBalance = new uint256[](tokens.length); for(uint i = 0; i < tokens.length; i++){ beforeBalance[i] = IERC20Upgradeable(tokens[i]).balanceOf(address(this)); } IVotiumBribes.claimParam[] memory request = new IVotiumBribes.claimParam[](tokens.length); for(uint x = 0; x < tokens.length; x++){ request[x] = IVotiumBribes.claimParam({ token: tokens[x], index: indexes[x], amount: amounts[x], merkleProof: merkleProofs[x] }); } votiumTree.claimMulti(account, request); for(uint i = 0; i < tokens.length; i++){ _handleRewardTransfer(token, IERC20Upgradeable(token).balanceOf(address(this)).sub(beforeBalance[i])); } require(beforeVaultBalance == _getBalance(), "Balance can\'t change"); require(beforePricePerFullShare == _getPricePerFullShare(), "Ppfs can\'t change"); } function claimBribesFromVotium( IVotiumBribes votiumTree, address account, address[] calldata tokens, uint256[] calldata indexes, uint256[] calldata amounts, bytes32[][] calldata merkleProofs ) external nonReentrant { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); uint256 beforePricePerFullShare = _getPricePerFullShare(); require(tokens.length == indexes.length && tokens.length == amounts.length && tokens.length == merkleProofs.length, "Length Mismatch"); uint256[] memory beforeBalance = new uint256[](tokens.length); for(uint i = 0; i < tokens.length; i++){ beforeBalance[i] = IERC20Upgradeable(tokens[i]).balanceOf(address(this)); } IVotiumBribes.claimParam[] memory request = new IVotiumBribes.claimParam[](tokens.length); for(uint x = 0; x < tokens.length; x++){ request[x] = IVotiumBribes.claimParam({ token: tokens[x], index: indexes[x], amount: amounts[x], merkleProof: merkleProofs[x] }); } votiumTree.claimMulti(account, request); for(uint i = 0; i < tokens.length; i++){ _handleRewardTransfer(token, IERC20Upgradeable(token).balanceOf(address(this)).sub(beforeBalance[i])); } require(beforeVaultBalance == _getBalance(), "Balance can\'t change"); require(beforePricePerFullShare == _getPricePerFullShare(), "Ppfs can\'t change"); } function claimBribesFromVotium( IVotiumBribes votiumTree, address account, address[] calldata tokens, uint256[] calldata indexes, uint256[] calldata amounts, bytes32[][] calldata merkleProofs ) external nonReentrant { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); uint256 beforePricePerFullShare = _getPricePerFullShare(); require(tokens.length == indexes.length && tokens.length == amounts.length && tokens.length == merkleProofs.length, "Length Mismatch"); uint256[] memory beforeBalance = new uint256[](tokens.length); for(uint i = 0; i < tokens.length; i++){ beforeBalance[i] = IERC20Upgradeable(tokens[i]).balanceOf(address(this)); } IVotiumBribes.claimParam[] memory request = new IVotiumBribes.claimParam[](tokens.length); for(uint x = 0; x < tokens.length; x++){ request[x] = IVotiumBribes.claimParam({ token: tokens[x], index: indexes[x], amount: amounts[x], merkleProof: merkleProofs[x] }); } votiumTree.claimMulti(account, request); for(uint i = 0; i < tokens.length; i++){ _handleRewardTransfer(token, IERC20Upgradeable(token).balanceOf(address(this)).sub(beforeBalance[i])); } require(beforeVaultBalance == _getBalance(), "Balance can\'t change"); require(beforePricePerFullShare == _getPricePerFullShare(), "Ppfs can\'t change"); } function claimBribesFromVotium( IVotiumBribes votiumTree, address account, address[] calldata tokens, uint256[] calldata indexes, uint256[] calldata amounts, bytes32[][] calldata merkleProofs ) external nonReentrant { _onlyGovernanceOrStrategist(); uint256 beforeVaultBalance = _getBalance(); uint256 beforePricePerFullShare = _getPricePerFullShare(); require(tokens.length == indexes.length && tokens.length == amounts.length && tokens.length == merkleProofs.length, "Length Mismatch"); uint256[] memory beforeBalance = new uint256[](tokens.length); for(uint i = 0; i < tokens.length; i++){ beforeBalance[i] = IERC20Upgradeable(tokens[i]).balanceOf(address(this)); } IVotiumBribes.claimParam[] memory request = new IVotiumBribes.claimParam[](tokens.length); for(uint x = 0; x < tokens.length; x++){ request[x] = IVotiumBribes.claimParam({ token: tokens[x], index: indexes[x], amount: amounts[x], merkleProof: merkleProofs[x] }); } votiumTree.claimMulti(account, request); for(uint i = 0; i < tokens.length; i++){ _handleRewardTransfer(token, IERC20Upgradeable(token).balanceOf(address(this)).sub(beforeBalance[i])); } require(beforeVaultBalance == _getBalance(), "Balance can\'t change"); require(beforePricePerFullShare == _getPricePerFullShare(), "Ppfs can\'t change"); } function _handleRewardTransfer(address token, uint256 amount) internal { if (token == BADGER){ _sendBadgerToTree(amount); _sentTokenToBribesReceiver(token, amount); } } function _handleRewardTransfer(address token, uint256 amount) internal { if (token == BADGER){ _sendBadgerToTree(amount); _sentTokenToBribesReceiver(token, amount); } } } else { function _sentTokenToBribesReceiver(address token, uint256 amount) internal { IERC20Upgradeable(token).safeTransfer(BRIBES_RECEIVER, amount); emit RewardsCollected(token, amount); } function _sendBadgerToTree(uint256 amount) internal { IERC20Upgradeable(BADGER).safeTransfer(BADGER_TREE, amount); emit TreeDistribution(BADGER, amount, block.number, block.timestamp); } function _getBalance() internal returns (uint256) { ISettV4 vault = ISettV4(IController(controller).vaults(want)); return vault.balance(); } function _getTotalSupply() internal returns (uint256) { ISettV4 vault = ISettV4(IController(controller).vaults(want)); return vault.totalSupply(); } function _getPricePerFullShare() internal returns (uint256) { ISettV4 vault = ISettV4(IController(controller).vaults(want)); return vault.getPricePerFullShare(); } function getBoostPayment() public view returns(uint256){ } function getName() external pure override returns (string memory) { return "veCVX Voting Strategy"; } function version() external pure returns (string memory) { return "1.6"; } function balanceOfPool() public view override returns (uint256) { return LOCKER.lockedBalanceOf(address(this)); } function isTendable() public view override returns (bool) { return false; } function getProtectedTokens() public view override returns (address[] memory) { address[] memory protectedTokens = new address[](3); protectedTokens[0] = want; return protectedTokens; } function _onlyNotProtectedTokens(address _asset) internal override { address[] memory protectedTokens = getProtectedTokens(); for (uint256 x = 0; x < protectedTokens.length; x++) { require( address(protectedTokens[x]) != _asset, "Asset is protected" ); } } function _onlyNotProtectedTokens(address _asset) internal override { address[] memory protectedTokens = getProtectedTokens(); for (uint256 x = 0; x < protectedTokens.length; x++) { require( address(protectedTokens[x]) != _asset, "Asset is protected" ); } } function _deposit(uint256 _amount) internal override { LOCKER.lock(address(this), _amount, getBoostPayment()); } function prepareWithdrawAll() external { manualProcessExpiredLocks(); } function _withdrawAll() internal override { require( LOCKER.lockedBalanceOf(address(this)) == 0 && LOCKER.balanceOf(address(this)) == 0, "You have to wait for unlock or have to manually rebalance out of it" ); } function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 max = balanceOfWant(); if(_amount > max){ LOCKER.processExpiredLocks(false); max = balanceOfWant(); } if (withdrawalSafetyCheck) { require( max >= _amount.mul(9_980).div(MAX_BPS), "Withdrawal Safety Check" } if (_amount > max) { return max; } return _amount; } function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 max = balanceOfWant(); if(_amount > max){ LOCKER.processExpiredLocks(false); max = balanceOfWant(); } if (withdrawalSafetyCheck) { require( max >= _amount.mul(9_980).div(MAX_BPS), "Withdrawal Safety Check" } if (_amount > max) { return max; } return _amount; } function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 max = balanceOfWant(); if(_amount > max){ LOCKER.processExpiredLocks(false); max = balanceOfWant(); } if (withdrawalSafetyCheck) { require( max >= _amount.mul(9_980).div(MAX_BPS), "Withdrawal Safety Check" } if (_amount > max) { return max; } return _amount; } function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 max = balanceOfWant(); if(_amount > max){ LOCKER.processExpiredLocks(false); max = balanceOfWant(); } if (withdrawalSafetyCheck) { require( max >= _amount.mul(9_980).div(MAX_BPS), "Withdrawal Safety Check" } if (_amount > max) { return max; } return _amount; } function harvest() public whenNotPaused returns (uint256) { _onlyAuthorizedActors(); uint256 _beforeReward = IERC20Upgradeable(reward).balanceOf(address(this)); LOCKER.getReward(address(this), false); uint256 earnedReward = IERC20Upgradeable(reward).balanceOf(address(this)).sub(_beforeReward); uint256 cvxCrvToGovernance = earnedReward.mul(performanceFeeGovernance).div(MAX_FEE); if(cvxCrvToGovernance > 0){ CVXCRV_VAULT.depositFor(IController(controller).rewards(), cvxCrvToGovernance); emit PerformanceFeeGovernance(IController(controller).rewards(), address(CVXCRV_VAULT), cvxCrvToGovernance, block.number, block.timestamp); } uint256 cvxCrvToStrategist = earnedReward.mul(performanceFeeStrategist).div(MAX_FEE); if(cvxCrvToStrategist > 0){ CVXCRV_VAULT.depositFor(strategist, cvxCrvToStrategist); emit PerformanceFeeStrategist(strategist, address(CVXCRV_VAULT), cvxCrvToStrategist, block.number, block.timestamp); } uint256 cvxCrvToTree = IERC20Upgradeable(reward).balanceOf(address(this)); CVXCRV_VAULT.depositFor(BADGER_TREE, cvxCrvToTree); uint256 cvxCRVAfterBalance = CVXCRV_VAULT.balanceOf(BADGER_TREE); emit TreeDistribution(address(CVXCRV_VAULT), cvxCRVAfterBalance.sub(cvxCRVInitialBalance), block.number, block.timestamp); } function harvest() public whenNotPaused returns (uint256) { _onlyAuthorizedActors(); uint256 _beforeReward = IERC20Upgradeable(reward).balanceOf(address(this)); LOCKER.getReward(address(this), false); uint256 earnedReward = IERC20Upgradeable(reward).balanceOf(address(this)).sub(_beforeReward); uint256 cvxCrvToGovernance = earnedReward.mul(performanceFeeGovernance).div(MAX_FEE); if(cvxCrvToGovernance > 0){ CVXCRV_VAULT.depositFor(IController(controller).rewards(), cvxCrvToGovernance); emit PerformanceFeeGovernance(IController(controller).rewards(), address(CVXCRV_VAULT), cvxCrvToGovernance, block.number, block.timestamp); } uint256 cvxCrvToStrategist = earnedReward.mul(performanceFeeStrategist).div(MAX_FEE); if(cvxCrvToStrategist > 0){ CVXCRV_VAULT.depositFor(strategist, cvxCrvToStrategist); emit PerformanceFeeStrategist(strategist, address(CVXCRV_VAULT), cvxCrvToStrategist, block.number, block.timestamp); } uint256 cvxCrvToTree = IERC20Upgradeable(reward).balanceOf(address(this)); CVXCRV_VAULT.depositFor(BADGER_TREE, cvxCrvToTree); uint256 cvxCRVAfterBalance = CVXCRV_VAULT.balanceOf(BADGER_TREE); emit TreeDistribution(address(CVXCRV_VAULT), cvxCRVAfterBalance.sub(cvxCRVInitialBalance), block.number, block.timestamp); } function harvest() public whenNotPaused returns (uint256) { _onlyAuthorizedActors(); uint256 _beforeReward = IERC20Upgradeable(reward).balanceOf(address(this)); LOCKER.getReward(address(this), false); uint256 earnedReward = IERC20Upgradeable(reward).balanceOf(address(this)).sub(_beforeReward); uint256 cvxCrvToGovernance = earnedReward.mul(performanceFeeGovernance).div(MAX_FEE); if(cvxCrvToGovernance > 0){ CVXCRV_VAULT.depositFor(IController(controller).rewards(), cvxCrvToGovernance); emit PerformanceFeeGovernance(IController(controller).rewards(), address(CVXCRV_VAULT), cvxCrvToGovernance, block.number, block.timestamp); } uint256 cvxCrvToStrategist = earnedReward.mul(performanceFeeStrategist).div(MAX_FEE); if(cvxCrvToStrategist > 0){ CVXCRV_VAULT.depositFor(strategist, cvxCrvToStrategist); emit PerformanceFeeStrategist(strategist, address(CVXCRV_VAULT), cvxCrvToStrategist, block.number, block.timestamp); } uint256 cvxCrvToTree = IERC20Upgradeable(reward).balanceOf(address(this)); CVXCRV_VAULT.depositFor(BADGER_TREE, cvxCrvToTree); uint256 cvxCRVAfterBalance = CVXCRV_VAULT.balanceOf(BADGER_TREE); emit TreeDistribution(address(CVXCRV_VAULT), cvxCRVAfterBalance.sub(cvxCRVInitialBalance), block.number, block.timestamp); } uint256 cvxCRVInitialBalance = CVXCRV_VAULT.balanceOf(BADGER_TREE); emit Harvest(earnedReward, block.number); return earnedReward; function tend() external whenNotPaused { } function reinvest() external whenNotPaused returns (uint256) { _onlyGovernance(); if (processLocksOnReinvest) { LOCKER.processExpiredLocks(false); } return toDeposit; } function reinvest() external whenNotPaused returns (uint256) { _onlyGovernance(); if (processLocksOnReinvest) { LOCKER.processExpiredLocks(false); } return toDeposit; } uint256 toDeposit = IERC20Upgradeable(want).balanceOf(address(this)); _deposit(toDeposit); function manualProcessExpiredLocks() public whenNotPaused { LOCKER.processExpiredLocks(false); } function checkUpkeep(bytes calldata checkData) external view returns (bool upkeepNeeded, bytes memory performData) { upkeepNeeded = LOCKER.lockedBalanceOf(address(this)) > LOCKER.balanceOf(address(this)); } function performUpkeep(bytes calldata performData) external { LOCKER.processExpiredLocks(false); } function manualSendCVXToVault() external whenNotPaused { _onlyGovernance(); uint256 cvxAmount = IERC20Upgradeable(want).balanceOf(address(this)); _transferToVault(cvxAmount); } function manualRebalance(uint256 toLock) external whenNotPaused { _onlyGovernance(); require(toLock <= MAX_BPS, "Max is 100%"); if (processLocksOnRebalance) { LOCKER.processExpiredLocks(false); } if (harvestOnRebalance) { harvest(); } IERC20Upgradeable(want).balanceOf(address(this)); uint256 totalCVXBalance = balanceOfWant.add(balanceInLock); if (newLockAmount <= balanceInLock) { return; } if (cvxToLock > maxCVX) { LOCKER.lock(address(this), maxCVX, getBoostPayment()); LOCKER.lock(address(this), cvxToLock, getBoostPayment()); } if(cvxLeft > 0){ _transferToVault(cvxLeft); } } function manualRebalance(uint256 toLock) external whenNotPaused { _onlyGovernance(); require(toLock <= MAX_BPS, "Max is 100%"); if (processLocksOnRebalance) { LOCKER.processExpiredLocks(false); } if (harvestOnRebalance) { harvest(); } IERC20Upgradeable(want).balanceOf(address(this)); uint256 totalCVXBalance = balanceOfWant.add(balanceInLock); if (newLockAmount <= balanceInLock) { return; } if (cvxToLock > maxCVX) { LOCKER.lock(address(this), maxCVX, getBoostPayment()); LOCKER.lock(address(this), cvxToLock, getBoostPayment()); } if(cvxLeft > 0){ _transferToVault(cvxLeft); } } function manualRebalance(uint256 toLock) external whenNotPaused { _onlyGovernance(); require(toLock <= MAX_BPS, "Max is 100%"); if (processLocksOnRebalance) { LOCKER.processExpiredLocks(false); } if (harvestOnRebalance) { harvest(); } IERC20Upgradeable(want).balanceOf(address(this)); uint256 totalCVXBalance = balanceOfWant.add(balanceInLock); if (newLockAmount <= balanceInLock) { return; } if (cvxToLock > maxCVX) { LOCKER.lock(address(this), maxCVX, getBoostPayment()); LOCKER.lock(address(this), cvxToLock, getBoostPayment()); } if(cvxLeft > 0){ _transferToVault(cvxLeft); } } uint256 balanceOfWant = uint256 balanceInLock = LOCKER.balanceOf(address(this)); uint256 newLockAmount = totalCVXBalance.mul(toLock).div(MAX_BPS); function manualRebalance(uint256 toLock) external whenNotPaused { _onlyGovernance(); require(toLock <= MAX_BPS, "Max is 100%"); if (processLocksOnRebalance) { LOCKER.processExpiredLocks(false); } if (harvestOnRebalance) { harvest(); } IERC20Upgradeable(want).balanceOf(address(this)); uint256 totalCVXBalance = balanceOfWant.add(balanceInLock); if (newLockAmount <= balanceInLock) { return; } if (cvxToLock > maxCVX) { LOCKER.lock(address(this), maxCVX, getBoostPayment()); LOCKER.lock(address(this), cvxToLock, getBoostPayment()); } if(cvxLeft > 0){ _transferToVault(cvxLeft); } } uint256 cvxToLock = newLockAmount.sub(balanceInLock); uint256 maxCVX = IERC20Upgradeable(want).balanceOf(address(this)); function manualRebalance(uint256 toLock) external whenNotPaused { _onlyGovernance(); require(toLock <= MAX_BPS, "Max is 100%"); if (processLocksOnRebalance) { LOCKER.processExpiredLocks(false); } if (harvestOnRebalance) { harvest(); } IERC20Upgradeable(want).balanceOf(address(this)); uint256 totalCVXBalance = balanceOfWant.add(balanceInLock); if (newLockAmount <= balanceInLock) { return; } if (cvxToLock > maxCVX) { LOCKER.lock(address(this), maxCVX, getBoostPayment()); LOCKER.lock(address(this), cvxToLock, getBoostPayment()); } if(cvxLeft > 0){ _transferToVault(cvxLeft); } } } else { uint256 cvxLeft = IERC20Upgradeable(want).balanceOf(address(this)); function manualRebalance(uint256 toLock) external whenNotPaused { _onlyGovernance(); require(toLock <= MAX_BPS, "Max is 100%"); if (processLocksOnRebalance) { LOCKER.processExpiredLocks(false); } if (harvestOnRebalance) { harvest(); } IERC20Upgradeable(want).balanceOf(address(this)); uint256 totalCVXBalance = balanceOfWant.add(balanceInLock); if (newLockAmount <= balanceInLock) { return; } if (cvxToLock > maxCVX) { LOCKER.lock(address(this), maxCVX, getBoostPayment()); LOCKER.lock(address(this), cvxToLock, getBoostPayment()); } if(cvxLeft > 0){ _transferToVault(cvxLeft); } } }
7,665,312
[ 1, 19302, 2430, 1399, 316, 2824, 1207, 16, 1410, 486, 506, 2319, 358, 598, 9446, 3970, 598, 9446, 8290, 1435, 225, 3186, 4058, 364, 6252, 6333, 18, 9363, 2427, 6865, 487, 14382, 715, 487, 3323, 225, 3186, 4058, 364, 4702, 598, 9446, 1031, 18, 9363, 2427, 6865, 487, 14382, 715, 487, 3323, 18, 225, 1021, 598, 9446, 1435, 445, 5972, 6635, 4692, 12088, 2545, 316, 326, 6252, 1865, 15600, 358, 598, 9446, 1898, 1450, 333, 225, 15987, 554, 1135, 628, 6865, 225, 2860, 848, 506, 283, 5768, 3149, 1368, 6865, 16, 578, 16859, 316, 4042, 30957, 225, 11217, 1359, 1656, 281, 1410, 2546, 506, 8249, 316, 333, 445, 225, 1439, 445, 7168, 353, 3723, 487, 1517, 6252, 848, 1240, 518, 3730, 87, 4953, 327, 3372, 364, 19980, 13730, 445, 17895, 26923, 1435, 3903, 5024, 31, 225, 2177, 17, 29111, 508, 364, 333, 6252, 364, 13694, 434, 26375, 6453, 225, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 8005, 4525, 353, 3360, 4525, 16, 868, 8230, 12514, 16709, 10784, 429, 288, 203, 565, 1450, 14060, 654, 39, 3462, 10784, 429, 364, 467, 654, 39, 3462, 10784, 429, 31, 203, 565, 1450, 5267, 10784, 429, 364, 1758, 31, 203, 565, 1450, 14060, 10477, 10784, 429, 364, 2254, 5034, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 38, 5857, 273, 1728, 67, 3784, 31, 203, 203, 203, 565, 1758, 1071, 5381, 16467, 3101, 67, 26557, 273, 374, 92, 26, 4848, 31644, 42, 71, 1105, 21, 70, 29003, 69, 12536, 6028, 69, 8898, 24942, 73, 11212, 74, 3707, 21, 38, 26, 72, 8285, 27, 37, 31, 203, 203, 565, 1599, 292, 4784, 4243, 1071, 5381, 14204, 31667, 273, 203, 3639, 1599, 292, 4784, 4243, 12, 20, 92, 24, 8148, 27, 5482, 74, 41, 26, 41, 29, 41, 29, 9470, 21, 39, 26, 24008, 42, 23, 70, 42, 8285, 73, 27, 27263, 5558, 42, 71, 1611, 25, 6334, 26, 1769, 203, 203, 565, 1758, 1071, 5381, 2030, 19384, 1777, 273, 203, 3639, 374, 92, 3461, 42, 10261, 74, 42, 8778, 40, 24, 23057, 25, 41, 5482, 2138, 5698, 74, 9452, 9793, 2138, 1578, 70, 20, 12124, 15168, 25, 73, 26, 31, 203, 203, 565, 1731, 1578, 1071, 5381, 2030, 19384, 6344, 67, 6616, 273, 203, 3639, 374, 92, 4449, 6669, 8285, 22, 73, 9222, 5608, 9470, 12648, 12648, 12648, 12648, 12648, 2787, 9449, 31, 203, 377, 203, 565, 467, 694, 88, 58, 24, 1071, 5381, 385, 58, 60, 5093, 58, 67, 27722, 2274, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./interfaces/DRToken.sol"; import "./TraitRegistry/ITraitRegistry.sol"; import "./interfaces/IRNG.sol"; import "hardhat/console.sol"; contract DRSpaceForge is Ownable { struct randomNumberRequest { address _address; uint16 mintedTokenId; uint256 random; bool fulfilled; } mapping(bytes32 => randomNumberRequest) randomNumberRequests; mapping(uint8 => uint8) public traitSizes; mapping(uint16 => bytes32) public tokenToHash; mapping(address => uint16[]) public userTokens; bool public locked; uint256 public unlockTime = 1635778800; // contracts DRToken public nft; IRNG public rnd; ITraitRegistry public traitRegistry; address BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; uint16 public nextMintedTokenId = 4002; event Forged(uint256 tokenXId, uint256 tokenYId, uint256 tokenWId, uint256 tokenZId, uint256 mintedTokenId, bytes32 requestHash); event Claimed(uint256 mintedTokenId, bytes32 requestHash); constructor( address erc721, address _tr, address _rndContractAddress ) { nft = DRToken(erc721); traitRegistry = ITraitRegistry(_tr); rnd = IRNG(_rndContractAddress); // trait 0 => 10% discount trait - all 128 pieces -> TODO: update trait 0 -> range start 4000 - end 7000 traitSizes[4] = 99; // trait 4 - Print trait - 99 pieces traitSizes[5] = 9; // trait 5 - ether card trait - 9 pieces traitSizes[6] = 4; // trait 6 - custom trait - 4 pieces traitSizes[7] = 63; // trait 7 - Robot Booster Pill redeem - 63 pieces } function forgeIT(uint256 tokenXId, uint256 tokenYId, uint256 tokenWId, uint256 tokenZId) public { uint16 mintedTokenId = nextMintedTokenId++; require(mintedTokenId < 4129, "DRSpaceForge: Max claim reached!"); require(!locked && getBlockTimestamp() > unlockTime, "DRSpaceForge: Contract locked"); require(nft.ownerOf(tokenXId) == msg.sender, "DRSpaceForge: Token X must be owned by message sender!"); require(nft.ownerOf(tokenYId) == msg.sender, "DRSpaceForge: Token Y must be owned by message sender!"); require(nft.ownerOf(tokenWId) == msg.sender, "DRSpaceForge: Token W must be owned by message sender!"); require(nft.ownerOf(tokenZId) == msg.sender, "DRSpaceForge: Token Z must be owned by message sender!"); require( validForge( getTokenCollectionById(tokenXId), getTokenCollectionById(tokenYId), getTokenCollectionById(tokenWId), getTokenCollectionById(tokenZId) ), "DRSpaceForge: Tokens cannot combine!" ); // burn tokens nft.transferFrom(msg.sender, BURN_ADDRESS, tokenXId); nft.transferFrom(msg.sender, BURN_ADDRESS, tokenYId); nft.transferFrom(msg.sender, BURN_ADDRESS, tokenWId); nft.transferFrom(msg.sender, BURN_ADDRESS, tokenZId); // Request a random number bytes32 hash = rnd.requestRandomNumberWithCallback(); // make sure we don't have hash collistions if(randomNumberRequests[hash].mintedTokenId > 0) { // request again! hash = rnd.requestRandomNumberWithCallback(); if(randomNumberRequests[hash].mintedTokenId > 0) { revert("DRSpaceForge: Random hash request collisions!"); } } // link token id to requested hash randomNumberRequests[hash] = randomNumberRequest(msg.sender, mintedTokenId, 0, false); // reverse mapping tokenToHash[mintedTokenId] = hash; userTokens[msg.sender].push(mintedTokenId); emit Forged(tokenXId, tokenYId, tokenWId, tokenZId, mintedTokenId, hash); } // 9,10,11,12 function validForge(uint256 collectionX, uint256 collectionY, uint256 collectionW, uint256 collectionZ) public pure returns ( bool ) { uint256 sum = collectionX + collectionY + collectionW + collectionZ; if (sum == 42) { // the meaning of life if( collectionX * collectionY * collectionW * collectionZ == 11880 ){ return true; } } return false; } // {name: "Summer High", uri: "summer-high", start: 5001, end: 5500 }, // {name: "Robot In The Sun", uri: "robot-in-the-sun", start: 5501, end: 6000 }, // {name: "Summer Fruits", uri: "summer-fruits", start: 6001, end: 6500 }, // {name: "Evolution", uri: "evolution", start: 6501, end: 7000 }, function getTokenCollectionById(uint256 _tokenId) public pure returns ( uint256 ) { require(_tokenId > 5000 && _tokenId < 7001, "DRSpaceForge: Token id does not participate"); _tokenId--; return _tokenId / 500 - 1; // remove 1 because of 4500-5000 gap } function process(uint256 _random, bytes32 _requestHash) public { require(msg.sender == address(rnd), "DRSpaceForge: Unauthorised"); // link _random result to requested hash randomNumberRequests[_requestHash].random = _random; randomNumberRequest storage request = randomNumberRequests[_requestHash]; // Allocate traits to this new token. uint16 tokensLeftToAssign = 4128 - request.mintedTokenId + 1; // console.log("tokensLeftToAssign", tokensLeftToAssign); // console.log(traitSizes[4], traitSizes[5], traitSizes[6], traitSizes[7]); for(uint8 i = 4; i < 8; i++) { // decide index by random uint256 _index = _random % tokensLeftToAssign; // console.log("_random", _random, "_index", _index); if(_index < traitSizes[i]) { // set trait traitRegistry.setTrait(i, request.mintedTokenId, true); // decrement traitSize traitSizes[i]--; } // shift _random = _random >> 8; } } function claim(uint16 tokenId) public { bytes32 _requestHash = tokenToHash[tokenId]; randomNumberRequest storage request = randomNumberRequests[_requestHash]; require(request._address == msg.sender, "DRSpaceForge: not request owner."); require(request.random > 0, "DRSpaceForge: random number needs to be higher than 0"); require(request.fulfilled == false, "DRSpaceForge: already claimed"); // mint the new token nft.mintTo(msg.sender, 8); request.fulfilled = true; emit Claimed(request.mintedTokenId, _requestHash); } function numberOfTokens(address _address) external view returns ( uint256 length) { return userTokens[_address].length; } function getStats(bytes32 hash) external view returns (address _address, uint16 mintedTokenId, uint256 random, bool fulfilled) { _address = randomNumberRequests[hash]._address; mintedTokenId = randomNumberRequests[hash].mintedTokenId; random = randomNumberRequests[hash].random; fulfilled = randomNumberRequests[hash].fulfilled; } function getStats(uint16 tokenId) external view returns (address _address, uint16 mintedTokenId, uint256 random, bool fulfilled) { bytes32 hash = tokenToHash[tokenId]; _address = randomNumberRequests[hash]._address; mintedTokenId = randomNumberRequests[hash].mintedTokenId; random = randomNumberRequests[hash].random; fulfilled = randomNumberRequests[hash].fulfilled; } function isInitialized() external view returns (bool) { // would be nice to be able to check rnd.isAuthorised() && nft.operator status return ( traitRegistry.addressCanModifyTrait(address(this), 4) && traitRegistry.addressCanModifyTrait(address(this), 5) && traitRegistry.addressCanModifyTrait(address(this), 6) && traitRegistry.addressCanModifyTrait(address(this), 7) ); } function getTraitSizes() public view returns (uint256, uint256, uint256, uint256) { return ( traitSizes[4], traitSizes[5], traitSizes[6], traitSizes[7] ); } function toggleLocked() public onlyOwner { locked = !locked; } function removeUnlockTime() public onlyOwner { unlockTime = block.timestamp; } function getBlockTimestamp() public view virtual returns (uint256) { return block.timestamp; } /// 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.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.0; interface DRToken { function mintTo(address _to, uint256 collection) external; function ownerOf(uint256 tokenId) external view returns (address owner); function transferFrom(address sender, address to, uint256 id) external; function balanceOf(address owner) external returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external returns (uint256); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ITraitRegistry { function getImplementer(uint16 traitID) external view returns (address); function addressCanModifyTrait(address, uint16) external view returns (bool); function addressCanModifyTraits(address, uint16[] memory) external view returns (bool); function hasTrait(uint16 traitID, uint16 tokenID) external view returns (bool); function setTrait(uint16 traitID, uint16 tokenID, bool) external; function setTraitOnTokens(uint16 traitID, uint16[] memory tokenID, bool[] memory) external; function owner() external view returns (address); function contractController(address) external view returns (bool); } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; interface IRNG { function requestRandomNumber() external returns (bytes32 requestId); function requestRandomNumberWithCallback() external returns (bytes32); function isRequestComplete(bytes32 requestId) external view returns (bool isCompleted); function randomNumber(bytes32 requestId) external view returns (uint256 randomNum); } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.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; } }
blackhole prevention methods
{ IERC20(_tracker).transfer(msg.sender, amount); }
13,552,776
[ 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, 288, 203, 3639, 467, 654, 39, 3462, 24899, 16543, 2934, 13866, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; import './TokenIterableMapping.sol'; import './BurnableUpgradeableMintableToken.sol'; contract PIERToken is BurnableUpgradeableMintableToken { string public constant name = "PIER Stable Token"; string public constant symbol = "PIER"; uint public constant decimals = 18; uint public constant initialSupply = 1000000000 * 10 ** 18; // Expected PIERToken price (target - 0.4 USD) uint256 targetPrice; // Struct holding mapping with the list of involved ERC20 Tokens. TokenIterableMapping.itmap basketTokens; /* * Events */ event TokenAddedToBasket (string indexed tokenSymbol, address indexed tokenContractAddress, uint256 price, uint256 amount); event TokenRemovedFromBasket(string indexed tokenSymbol); event TokenPriceChanged (string indexed tokenSymbol, uint256 newPrice, uint256 newAmount, uint256 oldPrice, uint256 oldAmount); event PriceChanged(uint256 newPrice); event MintedExtra (uint256 amount, uint256 price); event BurnedExtra (uint256 amount, uint256 price); constructor (address _teamMultisigWallet, uint256 _targetPrice) BurnableUpgradeableMintableToken(_teamMultisigWallet, name, symbol, initialSupply, decimals, false) public { targetPrice = _targetPrice; } // Add a new ERC20 to the Basket function addTokenToBasket(string tokenSymbol, address tokenContractAddress, uint256 price, uint256 amount) public onlyOwner returns (uint size) { TokenIterableMapping.insert(basketTokens, tokenSymbol, tokenContractAddress, price, amount); emit TokenAddedToBasket(tokenSymbol, tokenContractAddress, price, amount); return basketTokens.size; } // Remove a ERC20 from the Basket function removeTokenFromBasket(string tokenSymbol) public onlyOwner returns (uint size) { TokenIterableMapping.remove(basketTokens, tokenSymbol); emit TokenRemovedFromBasket(tokenSymbol); return basketTokens.size; } function updateSymbolPrice(string _tokenSymbol, uint256 newPrice) public onlyOwner returns (uint256 tokenPrice) { var (symbol, erc20Address, price, amount) = TokenIterableMapping.get(basketTokens, _tokenSymbol); TokenIterableMapping.insert(basketTokens, _tokenSymbol, erc20Address, newPrice, amount); emit TokenPriceChanged(_tokenSymbol, newPrice, amount, price, amount); uint256 newTokenPrice = calculatePrice(); emit PriceChanged(newTokenPrice); adjustTotalSupply(newTokenPrice); return newTokenPrice; } function calculatePrice() public view returns (uint256 tokenPrice) { uint256 total; for (var i = TokenIterableMapping.iterate_start(basketTokens); TokenIterableMapping.iterate_valid(basketTokens, i); i = TokenIterableMapping.iterate_next(basketTokens, i)) { var (symbol, erc20Address, price, amount) = TokenIterableMapping.iterate_get(basketTokens, i); total += price.mul(amount); } return total.div(totalSupply()); } function adjustTotalSupply(uint256 currentPrice) internal { uint256 toBeMintedAmount = calculateMintRequired(currentPrice); uint256 toBeBurnedAmount = calculateBurnRequired(currentPrice); if (toBeMintedAmount > 0) { mint(owner, toBeMintedAmount); emit MintedExtra (toBeMintedAmount, currentPrice); } if (toBeBurnedAmount > 0) { burnFrom(owner, toBeBurnedAmount); emit BurnedExtra (toBeBurnedAmount, currentPrice); } } function calculateMintRequired(uint256 currentPrice) internal view returns (uint256 adjustmentAmount) { return 0; // TODO: Add calculation logic } function calculateBurnRequired(uint256 currentPrice) internal view returns (uint256 adjustmentAmount) { return 0; // TODO: Add calculation logic } }
Remove a ERC20 from the Basket
function removeTokenFromBasket(string tokenSymbol) public onlyOwner returns (uint size) { TokenIterableMapping.remove(basketTokens, tokenSymbol); emit TokenRemovedFromBasket(tokenSymbol); return basketTokens.size; }
12,595,613
[ 1, 3288, 279, 4232, 39, 3462, 628, 326, 605, 7064, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1206, 1345, 1265, 11324, 12, 1080, 1147, 5335, 13, 1071, 1338, 5541, 1135, 261, 11890, 963, 13, 203, 565, 288, 203, 3639, 3155, 13668, 3233, 18, 4479, 12, 26219, 5157, 16, 1147, 5335, 1769, 203, 3639, 3626, 3155, 10026, 1265, 11324, 12, 2316, 5335, 1769, 203, 3639, 327, 12886, 5157, 18, 1467, 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 ]
pragma solidity 0.4.25; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; import 'openzeppelin-solidity/contracts/ownership/Ownable.sol'; import './token/OceanToken.sol'; import './tcr/OceanRegistry.sol'; /** @title Ocean Protocol Marketplace Contract @author Team: Fang Gong, Samer Sallam, Ahmed Ali, Sebastian Gerske */ contract OceanMarket is Ownable { using SafeMath for uint256; using SafeMath for uint; // ============ // DATA STRUCTURES: // ============ struct Asset { address owner; // owner of the Asset uint256 price; // price of asset bool active; // status of asset } mapping(bytes32 => Asset) private mAssets; // mapping assetId to Asset struct struct Payment { address sender; // payment sender address receiver; // provider or anyone (set by the sender of funds) PaymentState state; // payment state uint256 amount; // amount of tokens to be transferred uint256 date; // timestamp of the payment event (in sec.) uint256 expiration; // consumer may request refund after expiration timestamp (in sec.) bool paused; // pause the process of payment if dispute raised } enum PaymentState {Locked, Released, Refunded} mapping(bytes32 => Payment) private mPayments; // mapping from id to associated payment struct // limit period for reques of tokens mapping(address => uint256) private tokenRequest; // mapping from address to last time of request uint256 maxAmount = 10000 * 10 ** 18; // max amount of tokens user can get for each request uint256 minPeriod = 0; // min amount of time to wait before request token again // limit access to refund payment address private authAddress; address private disputeAddress; // marketplace global variables OceanToken public mToken; // todo: rename to registry // tcr global variable OceanRegistry public tcr; // ============ // EVENTS: // ============ event AssetRegistered(bytes32 indexed _assetId, address indexed _owner); event FrequentTokenRequest(address indexed _requester, uint256 _minPeriod); event LimitTokenRequest(address indexed _requester, uint256 _amount, uint256 _maxAmount); event PaymentReceived(bytes32 indexed _paymentId, address indexed _receiver, uint256 _amount, uint256 _expire); event PaymentReleased(bytes32 indexed _paymentId, address indexed _receiver); event PaymentRefunded(bytes32 indexed _paymentId, address indexed _sender); // ============ // modifier: // ============ modifier validAddress(address sender) { require(sender != address(0x0), 'Sender address is 0x0.'); _; } modifier isLocked(bytes32 _paymentId) { require(mPayments[_paymentId].state == PaymentState.Locked, 'State is not Locked'); _; } modifier isAuthContract() { require( msg.sender == authAddress || msg.sender == address(this) || msg.sender == disputeAddress, 'Sender is not an authorized contract.' ); _; } /** * @dev OceanMarket Constructor * @param _tokenAddress The deployed contract address of OceanToken * @param _registryAddress The deployed contract address of OceanRegistry * Runs only on initial contract creation. */ constructor(address _tokenAddress, address _registryAddress) public { require(_tokenAddress != address(0x0), 'Token address is 0x0.'); // instantiate Ocean token contract mToken = OceanToken(_tokenAddress); // todo: rename to registry // instance of registry tcr = OceanRegistry(_registryAddress); // set the token receiver to be marketplace mToken.setReceiver(address(this)); // create market contract instance in tcr tcr.setMarketInstance(address(this)); } /** * @dev provider register the new asset * @param assetId the integer identifier of new asset * @param price the integer representing price of new asset * @return valid Boolean indication of registration of new asset */ function register(bytes32 assetId, uint256 price) public validAddress(msg.sender) returns (bool success) { require(mAssets[assetId].owner == address(0), 'Owner address is not 0x0.'); mAssets[assetId] = Asset(msg.sender, price, false); mAssets[assetId].active = true; emit AssetRegistered(assetId, msg.sender); return true; } /** * @dev sender tranfer payment to OceanMarket contract * @param _paymentId the integer identifier of payment * @param _receiver the address of receiver * @param _amount the payment amount * @param _expire the expiration time in seconds * @return valid Boolean indication of payment is transferred */ function sendPayment( bytes32 _paymentId, address _receiver, uint256 _amount, uint256 _expire) public validAddress(msg.sender) returns (bool) { // consumer make payment to Market contract require(mToken.transferFrom(msg.sender, address(this), _amount), 'Token transferFrom failed.'); /* solium-disable-next-line security/no-block-members */ mPayments[_paymentId] = Payment(msg.sender, _receiver, PaymentState.Locked, _amount, block.timestamp, _expire, false); emit PaymentReceived(_paymentId, _receiver, _amount, _expire); return true; } /** * @dev dispute resolution calls this function to pause payment * @param _paymentId the integer identifier of payment (the same as dispute Id and service agreement Id) */ function pausePayment(bytes32 _paymentId) public isLocked(_paymentId) isAuthContract() { mPayments[_paymentId].paused = true; } /** * @dev dispute resolution calls this function to process payment * @param _paymentId the integer identifier of payment (the same as dispute Id and service agreement Id) * @param _release the boolean value indication of release payment * @param _refund the boolean value indication of refund payment */ function processPayment(bytes32 _paymentId, bool _release, bool _refund) public isLocked(_paymentId) isAuthContract() { // unpause the payment mPayments[_paymentId].paused = false; // process payment if (_release == true && _refund == false) { releasePayment(_paymentId); } else if (_release == false && _refund == true) { refundPayment(_paymentId); } } /** * @dev the consumer release payment to receiver * @param _paymentId the integer identifier of payment * @return valid Boolean indication of payment is released */ function releasePayment(bytes32 _paymentId) public isLocked(_paymentId) isAuthContract() returns (bool) { // payment must not be paused require(mPayments[_paymentId].paused == false, 'Payment is paused'); // update state to avoid re-entry attack mPayments[_paymentId].state = PaymentState.Released; require(mToken.transfer(mPayments[_paymentId].receiver, mPayments[_paymentId].amount), 'Token transfer failed.'); emit PaymentReleased(_paymentId, mPayments[_paymentId].receiver); return true; } /** * @dev the consumer get refunded payment from OceanMarket contract * @param _paymentId the integer identifier of payment * @return valid Boolean indication of payment is refunded */ function refundPayment(bytes32 _paymentId) public isLocked(_paymentId) isAuthContract() returns (bool) { // payment must not be paused require(mPayments[_paymentId].paused == false, 'Payment is paused'); // refund payment to consumer mPayments[_paymentId].state = PaymentState.Refunded; require(mToken.transfer(mPayments[_paymentId].sender, mPayments[_paymentId].amount), 'Token transfer failed.'); emit PaymentRefunded(_paymentId, mPayments[_paymentId].sender); return true; } /** * @dev verify the payment of consumer is received by OceanMarket * @param _paymentId the integer identifier of payment * @return valid Boolean indication of payment is received */ function verifyPaymentReceived(bytes32 _paymentId) public view returns (bool) { if (mPayments[_paymentId].state == PaymentState.Locked) { return true; } return false; } /** * @dev user can request some tokens for testing * @param amount the amount of tokens to be requested * @return valid Boolean indication of tokens are requested */ function requestTokens(uint256 amount) public validAddress(msg.sender) returns (bool) { /* solium-disable-next-line security/no-block-members */ if (block.timestamp < tokenRequest[msg.sender] + minPeriod) { emit FrequentTokenRequest(msg.sender, minPeriod); return false; } // amount should not exceed maxAmount if (amount > maxAmount) { require(mToken.transfer(msg.sender, maxAmount), 'Token transfer failed.'); emit LimitTokenRequest(msg.sender, amount, maxAmount); } else { require(mToken.transfer(msg.sender, amount), 'Token transfer failed.'); } /* solium-disable-next-line security/no-block-members */ tokenRequest[msg.sender] = block.timestamp; return true; } /** * @dev Owner can limit the amount and time for token request in Testing * @param _amount the max amount of tokens that can be requested * @param _period the min amount of time before next request */ function limitTokenRequest(uint _amount, uint _period) public onlyOwner() { // set min period of time before next request (in seconds) minPeriod = _period; // set max amount for each request maxAmount = _amount; } /** * @dev OceanMarket checks the voting result of OceanRegistry * @param listing the identifier of voting * @return valid Boolean indication of listing is whitelisted */ function checkListingStatus(bytes32 listing) public view returns (bool){ return tcr.isWhitelisted(listing); } /** * @dev OceanRegistry changes the asset status according to the voting result * @param assetId the integer identifier of asset in the voting * @return valid Boolean indication of asset is whitelisted */ function deactivateAsset(bytes32 assetId) public returns (bool){ // disable asset if it is not whitelisted in the registry if (!tcr.isWhitelisted(assetId)) { mAssets[assetId].active = false; } return true; } /** * @dev OceanMarket add the deployed address of OceanAuth contract * @return valid Boolean indication of contract address is updated */ function addAuthAddress() public validAddress(msg.sender) returns (bool) { // authAddress can only be set at deployment of Auth contract - only once require(authAddress == address(0), 'authAddress is not 0x0'); authAddress = msg.sender; return true; } /** * @dev OceanMarket add the deployed address of OceanDispute contract * @return valid Boolean indication of contract address is updated */ function addDisputeAddress() public validAddress(msg.sender) returns (bool) { // authAddress can only be set at deployment of Auth contract - only once require(disputeAddress == address(0), 'disputeAddress is not 0x0'); disputeAddress = msg.sender; return true; } /** * @dev OceanMarket generates bytes32 identifier for asset * @param contents the meta data information of asset as string * @return bytes32 as the identifier of asset */ function generateId(string contents) public pure returns (bytes32) { // Generate the hash of input string return bytes32(keccak256(abi.encodePacked(contents))); } /** * @dev OceanMarket generates bytes32 identifier for asset * @param contents the meta data information of asset as bytes * @return bytes32 as the identifier of asset */ function generateId(bytes contents) public pure returns (bytes32) { // Generate the hash of input bytes return bytes32(keccak256(abi.encodePacked(contents))); } /** * @dev OceanMarket check status of asset * @param assetId the integer identifier of asset * @return valid Boolean indication of asset is active or not */ function checkAsset(bytes32 assetId) public view returns (bool) { return mAssets[assetId].active; } /** * @dev OceanMarket check price of asset * @param assetId the integer identifier of asset * @return integer as price of asset */ function getAssetPrice(bytes32 assetId) public view returns (uint256) { return mAssets[assetId].price; } }
* @dev OceanMarket add the deployed address of OceanAuth contract @return valid Boolean indication of contract address is updated/ authAddress can only be set at deployment of Auth contract - only once
function addAuthAddress() public validAddress(msg.sender) returns (bool) { require(authAddress == address(0), 'authAddress is not 0x0'); authAddress = msg.sender; return true; }
890,595
[ 1, 51, 31393, 3882, 278, 527, 326, 19357, 1758, 434, 531, 31393, 1730, 6835, 327, 923, 3411, 1547, 829, 434, 6835, 1758, 353, 3526, 19, 1357, 1887, 848, 1338, 506, 444, 622, 6314, 434, 3123, 6835, 300, 1338, 3647, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 1730, 1887, 1435, 1071, 923, 1887, 12, 3576, 18, 15330, 13, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 1944, 1887, 422, 1758, 12, 20, 3631, 296, 1944, 1887, 353, 486, 374, 92, 20, 8284, 203, 3639, 1357, 1887, 273, 1234, 18, 15330, 31, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x6614958498796F80F9890CF8b8A73BeD1eA46Af7/sources/contracts/ParallaxOrbital.sol
* @notice Checks if provided shares amount is less than or equal to user's shares balance. Fails otherwise. @param strategyId An ID of an earning strategy. @param positionId An ID of a position. @param shares A fraction of the user's contribution./
function _onlyValidWithdrawalSharesAmount( uint256 strategyId, address user, uint256 positionId, uint256 shares ) private view { if (shares > positions[strategyId][user][positionId].shares) { revert OnlyValidWithdrawalSharesAmount(); } }
3,074,586
[ 1, 4081, 309, 2112, 24123, 3844, 353, 5242, 2353, 578, 3959, 358, 729, 1807, 540, 24123, 11013, 18, 8911, 87, 3541, 18, 225, 6252, 548, 1922, 1599, 434, 392, 425, 9542, 6252, 18, 225, 1754, 548, 1922, 1599, 434, 279, 1754, 18, 225, 24123, 432, 8330, 434, 326, 729, 1807, 24880, 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, 389, 3700, 1556, 1190, 9446, 287, 24051, 6275, 12, 203, 3639, 2254, 5034, 6252, 548, 16, 203, 3639, 1758, 729, 16, 203, 3639, 2254, 5034, 1754, 548, 16, 203, 3639, 2254, 5034, 24123, 203, 565, 262, 3238, 1476, 288, 203, 3639, 309, 261, 30720, 405, 6865, 63, 14914, 548, 6362, 1355, 6362, 3276, 548, 8009, 30720, 13, 288, 203, 5411, 15226, 5098, 1556, 1190, 9446, 287, 24051, 6275, 5621, 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 ]
pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT import "../../core/DaoRegistry.sol"; import "../../extensions/bank/Bank.sol"; import "../../core/DaoConstants.sol"; import "../../guards/MemberGuard.sol"; import "../../guards/AdapterGuard.sol"; import "../../utils/Signatures.sol"; import "../interfaces/IVoting.sol"; import "./Voting.sol"; import "./KickBadReporterAdapter.sol"; import "./SnapshotProposalContract.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; /** MIT License Copyright (c) 2020 Openlaw Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ contract OffchainVotingContract is IVoting, DaoConstants, MemberGuard, AdapterGuard, Signatures, Ownable { enum BadNodeError { OK, WRONG_PROPOSAL_ID, INVALID_CHOICE, AFTER_VOTING_PERIOD, BAD_SIGNATURE, INDEX_OUT_OF_BOUND } struct ProposalChallenge { address reporter; uint256 units; } uint256 public constant NB_CHOICES = 2; SnapshotProposalContract private _snapshotContract; KickBadReporterAdapter private _handleBadReporterAdapter; string public constant VOTE_RESULT_NODE_TYPE = "Message(uint64 timestamp,uint88 nbYes,uint88 nbNo,uint32 index,uint32 choice,bytes32 proposalId)"; string public constant ADAPTER_NAME = "OffchainVotingContract"; string public constant VOTE_RESULT_ROOT_TYPE = "Message(bytes32 root)"; bytes32 public constant VOTE_RESULT_NODE_TYPEHASH = keccak256(abi.encodePacked(VOTE_RESULT_NODE_TYPE)); bytes32 public constant VOTE_RESULT_ROOT_TYPEHASH = keccak256(abi.encodePacked(VOTE_RESULT_ROOT_TYPE)); bytes32 constant VotingPeriod = keccak256("offchainvoting.votingPeriod"); bytes32 constant GracePeriod = keccak256("offchainvoting.gracePeriod"); bytes32 constant FallbackThreshold = keccak256("offchainvoting.fallbackThreshold"); struct VoteStepParams { uint256 previousYes; uint256 previousNo; bytes32 proposalId; } struct Voting { uint256 snapshot; address reporter; bytes32 resultRoot; uint256 nbYes; uint256 nbNo; uint256 startingTime; uint256 gracePeriodStartingTime; bool isChallenged; bool forceFailed; mapping(address => bool) fallbackVotes; uint256 fallbackVotesCount; } struct VoteResultNode { uint32 choice; uint64 index; uint64 timestamp; uint88 nbNo; uint88 nbYes; bytes sig; bytes32 proposalId; bytes32[] proof; } modifier onlyBadReporterAdapter() { require(msg.sender == address(_handleBadReporterAdapter), "only:hbra"); _; } VotingContract public fallbackVoting; mapping(address => mapping(bytes32 => ProposalChallenge)) challengeProposals; mapping(address => mapping(bytes32 => Voting)) public votes; constructor( VotingContract _c, SnapshotProposalContract _spc, KickBadReporterAdapter _hbra, address _owner ) { require(address(_c) != address(0x0), "voting contract"); require(address(_spc) != address(0x0), "snapshot proposal"); require(address(_hbra) != address(0x0), "handle bad reporter"); fallbackVoting = _c; _snapshotContract = _spc; _handleBadReporterAdapter = _hbra; Ownable(_owner); } function adminFailProposal(DaoRegistry dao, bytes32 proposalId) external onlyOwner { Voting storage vote = votes[address(dao)][proposalId]; require(vote.startingTime > 0, "proposal has not started yet"); vote.forceFailed = true; } function hashResultRoot( DaoRegistry dao, address actionId, bytes32 resultRoot ) public view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", _snapshotContract.DOMAIN_SEPARATOR(dao, actionId), keccak256(abi.encode(VOTE_RESULT_ROOT_TYPEHASH, resultRoot)) ) ); } function getAdapterName() external pure override returns (string memory) { return ADAPTER_NAME; } function getChallengeDetails(DaoRegistry dao, bytes32 proposalId) external view returns (uint256, address) { return ( challengeProposals[address(dao)][proposalId].units, challengeProposals[address(dao)][proposalId].reporter ); } function hashVotingResultNode(VoteResultNode memory node) public pure returns (bytes32) { return keccak256( abi.encode( VOTE_RESULT_NODE_TYPEHASH, node.timestamp, node.nbYes, node.nbNo, node.index, node.choice, node.proposalId ) ); } function nodeHash( DaoRegistry dao, address actionId, VoteResultNode memory node ) public view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", _snapshotContract.DOMAIN_SEPARATOR(dao, actionId), hashVotingResultNode(node) ) ); } function configureDao( DaoRegistry dao, uint256 votingPeriod, uint256 gracePeriod, uint256 fallbackThreshold ) external onlyAdapter(dao) { dao.setConfiguration(VotingPeriod, votingPeriod); dao.setConfiguration(GracePeriod, gracePeriod); dao.setConfiguration(FallbackThreshold, fallbackThreshold); } /** What needs to be checked before submitting a vote result - if the grace period has ended, do nothing - if it's the first result, is this a right time to submit it? * is the diff between nbYes and nbNo +50% of the votes ? * is this after the voting period ? - if we already have a result that has been challenged * same as if there were no result yet - if we already have a result that has not been challenged * is the new one heavier than the previous one ? **/ function submitVoteResult( DaoRegistry dao, bytes32 proposalId, bytes32 resultRoot, VoteResultNode memory result, bytes memory rootSig ) external { Voting storage vote = votes[address(dao)][proposalId]; require(vote.snapshot > 0, "vote:not started"); if (vote.resultRoot == bytes32(0) || vote.isChallenged) { require( _readyToSubmitResult(dao, vote, result.nbYes, result.nbNo), "vote:notReadyToSubmitResult" ); } (address adapterAddress, ) = dao.proposals(proposalId); address reporter = ECDSA.recover( hashResultRoot(dao, adapterAddress, resultRoot), rootSig ); address memberAddr = dao.getAddressIfDelegated(reporter); require(isActiveMember(dao, memberAddr), "not active member"); uint256 nbMembers = BankExtension(dao.getExtensionAddress(BANK)).getPriorAmount( TOTAL, MEMBER_COUNT, vote.snapshot ); require(nbMembers - 1 == result.index, "index:member_count mismatch"); require( getBadNodeError( dao, proposalId, true, resultRoot, vote.snapshot, vote.gracePeriodStartingTime, nbMembers, result ) == BadNodeError.OK, "bad result" ); require( vote.nbYes + vote.nbNo < result.nbYes + result.nbNo, "result weight too low" ); if ( vote.gracePeriodStartingTime == 0 || vote.nbNo > vote.nbYes != result.nbNo > result.nbYes // check whether the new result changes the outcome ) { vote.gracePeriodStartingTime = block.timestamp; } vote.nbNo = result.nbNo; vote.nbYes = result.nbYes; vote.resultRoot = resultRoot; vote.reporter = memberAddr; vote.isChallenged = false; } function _readyToSubmitResult( DaoRegistry dao, Voting storage vote, uint256 nbYes, uint256 nbNo ) internal view returns (bool) { if (vote.forceFailed) { return false; } BankExtension bank = BankExtension(dao.getExtensionAddress(BANK)); uint256 totalWeight = bank.getPriorAmount(TOTAL, UNITS, vote.snapshot); uint256 unvotedWeights = totalWeight - nbYes - nbNo; uint256 diff; if (nbYes > nbNo) { diff = nbYes - nbNo; } else { diff = nbNo - nbYes; } if (diff > unvotedWeights) { return true; } uint256 votingPeriod = dao.getConfiguration(VotingPeriod); return vote.startingTime + votingPeriod <= block.timestamp; } function getSenderAddress( DaoRegistry dao, address actionId, bytes memory data, address ) external view override returns (address) { SnapshotProposalContract.ProposalMessage memory proposal = abi.decode(data, (SnapshotProposalContract.ProposalMessage)); return ECDSA.recover( _snapshotContract.hashMessage(dao, actionId, proposal), proposal.sig ); } function startNewVotingForProposal( DaoRegistry dao, bytes32 proposalId, bytes memory data ) public override onlyAdapter(dao) { SnapshotProposalContract.ProposalMessage memory proposal = abi.decode(data, (SnapshotProposalContract.ProposalMessage)); (bool success, uint256 blockNumber) = _stringToUint(proposal.payload.snapshot); require(success, "snapshot conversion error"); BankExtension bank = BankExtension(dao.getExtensionAddress(BANK)); bytes32 proposalHash = _snapshotContract.hashMessage(dao, msg.sender, proposal); address addr = ECDSA.recover(proposalHash, proposal.sig); address memberAddr = dao.getAddressIfDelegated(addr); require(bank.balanceOf(memberAddr, UNITS) > 0, "noActiveMember"); require( blockNumber <= block.number, "snapshot block number should not be in the future" ); require(blockNumber > 0, "block number cannot be 0"); votes[address(dao)][proposalId].startingTime = block.timestamp; votes[address(dao)][proposalId].snapshot = blockNumber; } function _fallbackVotingActivated( DaoRegistry dao, uint256 fallbackVotesCount ) internal view returns (bool) { return fallbackVotesCount > (dao.getNbMembers() * 100) / dao.getConfiguration(FallbackThreshold); } /** possible results here: 0: has not started 1: tie 2: pass 3: not pass 4: in progress */ function voteResult(DaoRegistry dao, bytes32 proposalId) external view override returns (VotingState state) { Voting storage vote = votes[address(dao)][proposalId]; if (vote.startingTime == 0) { return VotingState.NOT_STARTED; } if (vote.forceFailed) { return VotingState.NOT_PASS; } if (_fallbackVotingActivated(dao, vote.fallbackVotesCount)) { return fallbackVoting.voteResult(dao, proposalId); } if (vote.isChallenged) { return VotingState.IN_PROGRESS; } uint256 votingPeriod = dao.getConfiguration(VotingPeriod); //if the vote has started but the voting period has not passed yet, it's in progress if (block.timestamp < vote.startingTime + votingPeriod) { return VotingState.IN_PROGRESS; } uint256 gracePeriod = dao.getConfiguration(GracePeriod); //if no result have been submitted but we are before grace + voting period, then the proposal is GRACE_PERIOD if ( vote.gracePeriodStartingTime == 0 && block.timestamp < vote.startingTime + gracePeriod + votingPeriod ) { return VotingState.GRACE_PERIOD; } //if the vote has started but the voting period has not passed yet, it's in progress if (block.timestamp < vote.gracePeriodStartingTime + gracePeriod) { return VotingState.GRACE_PERIOD; } if (vote.nbYes > vote.nbNo) { return VotingState.PASS; } if (vote.nbYes < vote.nbNo) { return VotingState.NOT_PASS; } return VotingState.TIE; } function challengeBadFirstNode( DaoRegistry dao, bytes32 proposalId, VoteResultNode memory node ) external { require(node.index == 0, "only first node"); Voting storage vote = votes[address(dao)][proposalId]; (address adapterAddress, ) = dao.proposals(proposalId); require(vote.resultRoot != bytes32(0), "no result available yet!"); bytes32 hashCurrent = nodeHash(dao, adapterAddress, node); //check that the step is indeed part of the result require( MerkleProof.verify(node.proof, vote.resultRoot, hashCurrent), "proof:bad" ); (address actionId, ) = dao.proposals(proposalId); if (_checkStep(dao, actionId, node, VoteStepParams(0, 0, proposalId))) { _challengeResult(dao, proposalId); } } function challengeBadNode( DaoRegistry dao, bytes32 proposalId, VoteResultNode memory node ) external { Voting storage vote = votes[address(dao)][proposalId]; BankExtension bank = BankExtension(dao.getExtensionAddress(BANK)); if ( getBadNodeError( dao, proposalId, false, vote.resultRoot, vote.snapshot, vote.gracePeriodStartingTime, bank.getPriorAmount(TOTAL, MEMBER_COUNT, vote.snapshot), node ) != BadNodeError.OK ) { _challengeResult(dao, proposalId); } } function _isValidChoice(uint256 choice) internal pure returns (bool) { return choice > 0 && choice < NB_CHOICES + 1; } function getBadNodeError( DaoRegistry dao, bytes32 proposalId, bool submitNewVote, bytes32 resultRoot, uint256 blockNumber, uint256 gracePeriodStartingTime, uint256 nbMembers, VoteResultNode memory node ) public view returns (BadNodeError) { (address adapterAddress, ) = dao.proposals(proposalId); require(resultRoot != bytes32(0), "no result available yet!"); bytes32 hashCurrent = nodeHash(dao, adapterAddress, node); //check that the step is indeed part of the result require( MerkleProof.verify(node.proof, resultRoot, hashCurrent), "proof:bad" ); if (node.index >= nbMembers) { return BadNodeError.INDEX_OUT_OF_BOUND; } address account = dao.getMemberAddress(node.index); //return 1 if yes, 2 if no and 0 if the vote is incorrect address voter = dao.getPriorDelegateKey(account, blockNumber); (address actionId, ) = dao.proposals(proposalId); //invalid choice if ( (node.sig.length == 0 && node.choice != 0) || // no vote (node.sig.length > 0 && !_isValidChoice(node.choice)) ) { return BadNodeError.INVALID_CHOICE; } //invalid proposal hash if (node.proposalId != proposalId) { return BadNodeError.WRONG_PROPOSAL_ID; } //has voted outside of the voting time if (!submitNewVote && node.timestamp > gracePeriodStartingTime) { return BadNodeError.AFTER_VOTING_PERIOD; } //bad signature if ( node.sig.length > 0 && // a vote has happened !_hasVoted( dao, actionId, voter, node.timestamp, node.proposalId, node.choice, node.sig ) ) { return BadNodeError.BAD_SIGNATURE; } return BadNodeError.OK; } function challengeBadStep( DaoRegistry dao, bytes32 proposalId, VoteResultNode memory nodePrevious, VoteResultNode memory nodeCurrent ) external { Voting storage vote = votes[address(dao)][proposalId]; bytes32 resultRoot = vote.resultRoot; (address adapterAddress, ) = dao.proposals(proposalId); require(resultRoot != bytes32(0), "no result available yet!"); bytes32 hashCurrent = nodeHash(dao, adapterAddress, nodeCurrent); bytes32 hashPrevious = nodeHash(dao, adapterAddress, nodePrevious); require( MerkleProof.verify(nodeCurrent.proof, resultRoot, hashCurrent), "proof check for current invalid for current node" ); require( MerkleProof.verify(nodePrevious.proof, resultRoot, hashPrevious), "proof check for previous invalid for previous node" ); require( nodeCurrent.index == nodePrevious.index + 1, "those nodes are not consecutive" ); (address actionId, ) = dao.proposals(proposalId); VoteStepParams memory params = VoteStepParams(nodePrevious.nbYes, nodePrevious.nbNo, proposalId); if (_checkStep(dao, actionId, nodeCurrent, params)) { _challengeResult(dao, proposalId); } } function requestFallback(DaoRegistry dao, bytes32 proposalId) external onlyMember(dao) { require( votes[address(dao)][proposalId].fallbackVotes[msg.sender] == false, "the member has already voted for this vote to fallback" ); votes[address(dao)][proposalId].fallbackVotes[msg.sender] = true; votes[address(dao)][proposalId].fallbackVotesCount += 1; if ( _fallbackVotingActivated( dao, votes[address(dao)][proposalId].fallbackVotesCount ) ) { fallbackVoting.startNewVotingForProposal(dao, proposalId, ""); } } function _checkStep( DaoRegistry dao, address actionId, VoteResultNode memory node, VoteStepParams memory params ) internal view returns (bool) { Voting storage vote = votes[address(dao)][params.proposalId]; address account = dao.getMemberAddress(node.index); address voter = dao.getPriorDelegateKey(account, vote.snapshot); BankExtension bank = BankExtension(dao.getExtensionAddress(BANK)); uint256 weight = bank.getPriorAmount(account, UNITS, vote.snapshot); if (node.choice == 0) { if (params.previousYes != node.nbYes) { return true; } else if (params.previousNo != node.nbNo) { return true; } } if ( _hasVoted( dao, actionId, voter, node.timestamp, node.proposalId, 1, node.sig ) ) { if (params.previousYes + weight != node.nbYes) { return true; } else if (params.previousNo != node.nbNo) { return true; } } if ( _hasVoted( dao, actionId, voter, node.timestamp, node.proposalId, 2, node.sig ) ) { if (params.previousYes != node.nbYes) { return true; } else if (params.previousNo + weight != node.nbNo) { return true; } } return false; } function sponsorChallengeProposal( DaoRegistry dao, bytes32 proposalId, address sponsoredBy ) external onlyBadReporterAdapter { dao.sponsorProposal(proposalId, sponsoredBy, address(this)); } function processChallengeProposal(DaoRegistry dao, bytes32 proposalId) external onlyBadReporterAdapter { dao.processProposal(proposalId); } function _challengeResult(DaoRegistry dao, bytes32 proposalId) internal { BankExtension bank = BankExtension(dao.getExtensionAddress(BANK)); votes[address(dao)][proposalId].isChallenged = true; address challengedReporter = votes[address(dao)][proposalId].reporter; bytes32 challengeProposalId = keccak256( abi.encodePacked( proposalId, votes[address(dao)][proposalId].resultRoot ) ); dao.submitProposal(challengeProposalId); uint256 units = bank.balanceOf(challengedReporter, UNITS); challengeProposals[address(dao)][ challengeProposalId ] = ProposalChallenge(challengedReporter, units); // Burns / subtracts from member's balance the number of units to burn. bank.subtractFromBalance(challengedReporter, UNITS, units); // Burns / subtracts from member's balance the number of loot to burn. // bank.subtractFromBalance(memberToKick, LOOT, kick.lootToBurn); bank.addToBalance(challengedReporter, LOOT, units); } function _hasVoted( DaoRegistry dao, address actionId, address voter, uint64 timestamp, bytes32 proposalId, uint32 choiceIdx, bytes memory sig ) internal view returns (bool) { bytes32 voteHash = _snapshotContract.hashVote( dao, actionId, SnapshotProposalContract.VoteMessage( timestamp, SnapshotProposalContract.VotePayload(choiceIdx, proposalId) ) ); return ECDSA.recover(voteHash, sig) == voter; } function _stringToUint(string memory s) internal pure returns (bool success, uint256 result) { bytes memory b = bytes(s); result = 0; success = false; for (uint256 i = 0; i < b.length; i++) { if (uint8(b[i]) >= 48 && uint8(b[i]) <= 57) { result = result * 10 + (uint8(b[i]) - 48); success = true; } else { result = 0; success = false; break; } } return (success, result); } }
check that the step is indeed part of the result
function challengeBadFirstNode( DaoRegistry dao, bytes32 proposalId, VoteResultNode memory node ) external { require(node.index == 0, "only first node"); Voting storage vote = votes[address(dao)][proposalId]; (address adapterAddress, ) = dao.proposals(proposalId); require(vote.resultRoot != bytes32(0), "no result available yet!"); bytes32 hashCurrent = nodeHash(dao, adapterAddress, node); require( MerkleProof.verify(node.proof, vote.resultRoot, hashCurrent), "proof:bad" ); (address actionId, ) = dao.proposals(proposalId); if (_checkStep(dao, actionId, node, VoteStepParams(0, 0, proposalId))) { _challengeResult(dao, proposalId); } }
12,986,067
[ 1, 1893, 716, 326, 2235, 353, 316, 323, 329, 1087, 434, 326, 563, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12948, 6434, 3759, 907, 12, 203, 3639, 463, 6033, 4243, 15229, 16, 203, 3639, 1731, 1578, 14708, 548, 16, 203, 3639, 27540, 1253, 907, 3778, 756, 203, 565, 262, 3903, 288, 203, 3639, 2583, 12, 2159, 18, 1615, 422, 374, 16, 315, 3700, 1122, 756, 8863, 203, 3639, 776, 17128, 2502, 12501, 273, 19588, 63, 2867, 12, 2414, 83, 13, 6362, 685, 8016, 548, 15533, 203, 3639, 261, 2867, 4516, 1887, 16, 262, 273, 15229, 18, 685, 22536, 12, 685, 8016, 548, 1769, 203, 3639, 2583, 12, 25911, 18, 2088, 2375, 480, 1731, 1578, 12, 20, 3631, 315, 2135, 563, 2319, 4671, 4442, 1769, 203, 3639, 1731, 1578, 1651, 3935, 273, 756, 2310, 12, 2414, 83, 16, 4516, 1887, 16, 756, 1769, 203, 3639, 2583, 12, 203, 5411, 31827, 20439, 18, 8705, 12, 2159, 18, 24207, 16, 12501, 18, 2088, 2375, 16, 1651, 3935, 3631, 203, 5411, 315, 24207, 30, 8759, 6, 203, 3639, 11272, 203, 203, 3639, 261, 2867, 1301, 548, 16, 262, 273, 15229, 18, 685, 22536, 12, 685, 8016, 548, 1769, 203, 203, 3639, 309, 261, 67, 1893, 4160, 12, 2414, 83, 16, 1301, 548, 16, 756, 16, 27540, 4160, 1370, 12, 20, 16, 374, 16, 14708, 548, 20349, 288, 203, 5411, 389, 25092, 1253, 12, 2414, 83, 16, 14708, 548, 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 ]
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 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 Contract that is aware of time. Useful for tests - like this * we can mock time. */ contract TimeAware is Ownable { /** * @dev Returns current time. */ function getTime() public view returns (uint) { return now; } } /** * @dev Contract that holds pending withdrawals. Responsible for withdrawals. */ contract Withdrawable { mapping(address => uint) private pendingWithdrawals; event Withdrawal(address indexed receiver, uint amount); event BalanceChanged(address indexed _address, uint oldBalance, uint newBalance); /** * Returns amount of wei that given address is able to withdraw. */ function getPendingWithdrawal(address _address) public view returns (uint) { return pendingWithdrawals[_address]; } /** * Add pending withdrawal for an address. */ function addPendingWithdrawal(address _address, uint _amount) internal { require(_address != 0x0); uint oldBalance = pendingWithdrawals[_address]; pendingWithdrawals[_address] += _amount; emit BalanceChanged(_address, oldBalance, oldBalance + _amount); } /** * Withdraws all pending withdrawals. */ function withdraw() external { uint amount = getPendingWithdrawal(msg.sender); require(amount > 0); pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(amount); emit Withdrawal(msg.sender, amount); emit BalanceChanged(msg.sender, amount, 0); } } /** * @dev This contract takes care of painting on canvases, returning artworks and creating ones. */ contract CanvasFactory is TimeAware { //@dev It means canvas is not finished yet, and bidding is not possible. uint8 public constant STATE_NOT_FINISHED = 0; //@dev there is ongoing bidding and anybody can bid. If there canvas can have // assigned owner, but it can change if someone will over-bid him. uint8 public constant STATE_INITIAL_BIDDING = 1; //@dev canvas has been sold, and has the owner uint8 public constant STATE_OWNED = 2; uint8 public constant WIDTH = 64; uint8 public constant HEIGHT = 64; uint32 public constant PIXEL_COUNT = 4096; //WIDTH * HEIGHT doesn&#39;t work for some reason uint32 public constant MAX_CANVAS_COUNT = 1000; uint8 public constant MAX_ACTIVE_CANVAS = 12; Canvas[] canvases; uint32 public activeCanvasCount = 0; event PixelPainted(uint32 indexed canvasId, uint32 index, uint8 color, address indexed painter); event CanvasFinished(uint32 indexed canvasId); event CanvasCreated(uint indexed canvasId); modifier notFinished(uint32 _canvasId) { require(!isCanvasFinished(_canvasId)); _; } modifier finished(uint32 _canvasId) { require(isCanvasFinished(_canvasId)); _; } modifier validPixelIndex(uint32 _pixelIndex) { require(_pixelIndex < PIXEL_COUNT); _; } /** * @notice Creates new canvas. There can&#39;t be more canvases then MAX_CANVAS_COUNT. * There can&#39;t be more unfinished canvases than MAX_ACTIVE_CANVAS. */ function createCanvas() external returns (uint canvasId) { require(canvases.length < MAX_CANVAS_COUNT); require(activeCanvasCount < MAX_ACTIVE_CANVAS); uint id = canvases.push(Canvas(STATE_NOT_FINISHED, 0x0, 0, 0, false)) - 1; emit CanvasCreated(id); activeCanvasCount++; return id; } /** * @notice Sets pixel. Given canvas can&#39;t be yet finished. */ function setPixel(uint32 _canvasId, uint32 _index, uint8 _color) external notFinished(_canvasId) validPixelIndex(_index) { require(_color > 0); Canvas storage canvas = _getCanvas(_canvasId); Pixel storage pixel = canvas.pixels[_index]; // pixel always has a painter. If it&#39;s equal to address(0) it means // that pixel hasn&#39;t been set. if (pixel.painter == 0x0) { canvas.paintedPixelsCount++; } else { canvas.addressToCount[pixel.painter]--; } canvas.addressToCount[msg.sender]++; canvas.pixels[_index] = Pixel(_color, msg.sender); if (_isCanvasFinished(canvas)) { activeCanvasCount--; canvas.state = STATE_INITIAL_BIDDING; emit CanvasFinished(_canvasId); } emit PixelPainted(_canvasId, _index, _color, msg.sender); } /** * @notice Returns full bitmap for given canvas. */ function getCanvasBitmap(uint32 _canvasId) external view returns (uint8[]) { Canvas storage canvas = _getCanvas(_canvasId); uint8[] memory result = new uint8[](PIXEL_COUNT); for (uint32 i = 0; i < PIXEL_COUNT; i++) { result[i] = canvas.pixels[i].color; } return result; } /** * @notice Returns how many pixels has been already set. */ function getCanvasPaintedPixelsCount(uint32 _canvasId) public view returns (uint32) { return _getCanvas(_canvasId).paintedPixelsCount; } function getPixelCount() external pure returns (uint) { return PIXEL_COUNT; } /** * @notice Returns amount of created canvases. */ function getCanvasCount() public view returns (uint) { return canvases.length; } /** * @notice Returns true if the canvas has been already finished. */ function isCanvasFinished(uint32 _canvasId) public view returns (bool) { return _isCanvasFinished(_getCanvas(_canvasId)); } /** * @notice Returns the author of given pixel. */ function getPixelAuthor(uint32 _canvasId, uint32 _pixelIndex) public view validPixelIndex(_pixelIndex) returns (address) { return _getCanvas(_canvasId).pixels[_pixelIndex].painter; } /** * @notice Returns number of pixels set by given address. */ function getPaintedPixelsCountByAddress(address _address, uint32 _canvasId) public view returns (uint32) { Canvas storage canvas = _getCanvas(_canvasId); return canvas.addressToCount[_address]; } function _isCanvasFinished(Canvas canvas) internal pure returns (bool) { return canvas.paintedPixelsCount == PIXEL_COUNT; } function _getCanvas(uint32 _canvasId) internal view returns (Canvas storage) { require(_canvasId < canvases.length); return canvases[_canvasId]; } struct Pixel { uint8 color; address painter; } struct Canvas { /** * Map of all pixels. */ mapping(uint32 => Pixel) pixels; uint8 state; /** * Owner of canvas. Canvas doesn&#39;t have an owner until initial bidding ends. */ address owner; /** * Numbers of pixels set. Canvas will be considered finished when all pixels will be set. * Technically it means that setPixelsCount == PIXEL_COUNT */ uint32 paintedPixelsCount; mapping(address => uint32) addressToCount; /** * Initial bidding finish time. */ uint initialBiddingFinishTime; /** * If commission from initial bidding has been paid. */ bool isCommissionPaid; /** * @dev if address has been paid a reward for drawing. */ mapping(address => bool) isAddressPaid; } } /** * @dev This contract takes care of initial bidding. */ contract BiddableCanvas is CanvasFactory, Withdrawable { /** * As it&#39;s hard to operate on floating numbers, each fee will be calculated like this: * PRICE * COMMISSION / COMMISSION_DIVIDER. It&#39;s impossible to keep float number here. * * ufixed COMMISSION = 0.039; may seem useful, but it&#39;s not possible to multiply ufixed * uint. */ uint public constant COMMISSION = 39; uint public constant COMMISSION_DIVIDER = 1000; uint8 public constant ACTION_INITIAL_BIDDING = 0; uint8 public constant ACTION_SELL_OFFER_ACCEPTED = 1; uint8 public constant ACTION_BUY_OFFER_ACCEPTED = 2; uint public constant BIDDING_DURATION = 48 hours; mapping(uint32 => Bid) bids; mapping(address => uint32) addressToCount; uint public minimumBidAmount = 0.1 ether; event BidPosted(uint32 indexed canvasId, address indexed bidder, uint amount, uint finishTime); event RewardAddedToWithdrawals(uint32 indexed canvasId, address indexed toAddress, uint amount); event CommissionAddedToWithdrawals(uint32 indexed canvasId, uint amount, uint8 indexed action); modifier stateBidding(uint32 _canvasId) { require(getCanvasState(_canvasId) == STATE_INITIAL_BIDDING); _; } modifier stateOwned(uint32 _canvasId) { require(getCanvasState(_canvasId) == STATE_OWNED); _; } /** * Ensures that canvas&#39;s saved state is STATE_OWNED. * * Because initial bidding is based on current time, we had to find a way to * trigger saving new canvas state. Every transaction (not a call) that * requires state owned should use it modifier as a last one. * * Thank&#39;s to that, we can make sure, that canvas state gets updated. */ modifier forceOwned(uint32 _canvasId) { Canvas storage canvas = _getCanvas(_canvasId); if (canvas.state != STATE_OWNED) { canvas.state = STATE_OWNED; } _; } /** * Places bid for canvas that is in the state STATE_INITIAL_BIDDING. * If somebody is outbid his pending withdrawals will be to topped up. */ function makeBid(uint32 _canvasId) external payable stateBidding(_canvasId) { Canvas storage canvas = _getCanvas(_canvasId); Bid storage oldBid = bids[_canvasId]; if (msg.value < minimumBidAmount || msg.value <= oldBid.amount) { revert(); } if (oldBid.bidder != 0x0 && oldBid.amount > 0) { //return old bidder his money addPendingWithdrawal(oldBid.bidder, oldBid.amount); } uint finishTime = canvas.initialBiddingFinishTime; if (finishTime == 0) { canvas.initialBiddingFinishTime = getTime() + BIDDING_DURATION; } bids[_canvasId] = Bid(msg.sender, msg.value); if (canvas.owner != 0x0) { addressToCount[canvas.owner]--; } canvas.owner = msg.sender; addressToCount[msg.sender]++; emit BidPosted(_canvasId, msg.sender, msg.value, canvas.initialBiddingFinishTime); } /** * @notice Returns last bid for canvas. If the initial bidding has been * already finished that will be winning offer. */ function getLastBidForCanvas(uint32 _canvasId) external view returns (uint32 canvasId, address bidder, uint amount, uint finishTime) { Bid storage bid = bids[_canvasId]; Canvas storage canvas = _getCanvas(_canvasId); return (_canvasId, bid.bidder, bid.amount, canvas.initialBiddingFinishTime); } /** * @notice Returns current canvas state. */ function getCanvasState(uint32 _canvasId) public view returns (uint8) { Canvas storage canvas = _getCanvas(_canvasId); if (canvas.state != STATE_INITIAL_BIDDING) { //if state is set to owned, or not finished //it means it doesn&#39;t depend on current time - //we don&#39;t have to double check return canvas.state; } //state initial bidding - as that state depends on //current time, we have to double check if initial bidding //hasn&#39;t finish yet uint finishTime = canvas.initialBiddingFinishTime; if (finishTime == 0 || finishTime > getTime()) { return STATE_INITIAL_BIDDING; } else { return STATE_OWNED; } } /** * @notice Returns all canvas&#39; id for a given state. */ function getCanvasByState(uint8 _state) external view returns (uint32[]) { uint size; if (_state == STATE_NOT_FINISHED) { size = activeCanvasCount; } else { size = getCanvasCount() - activeCanvasCount; } uint32[] memory result = new uint32[](size); uint currentIndex = 0; for (uint32 i = 0; i < canvases.length; i++) { if (getCanvasState(i) == _state) { result[currentIndex] = i; currentIndex++; } } return _slice(result, 0, currentIndex); } /** * @notice Returns reward for painting pixels in wei. That reward is proportional * to number of set pixels. For example let&#39;s assume that the address has painted * 2048 pixels, which is 50% of all pixels. He will be rewarded * with 50% of winning bid minus fee. */ function calculateReward(uint32 _canvasId, address _address) public view stateOwned(_canvasId) returns (uint32 pixelsCount, uint reward, bool isPaid) { Bid storage bid = bids[_canvasId]; Canvas storage canvas = _getCanvas(_canvasId); uint32 paintedPixels = getPaintedPixelsCountByAddress(_address, _canvasId); uint pricePerPixel = _calculatePricePerPixel(bid.amount); uint _reward = paintedPixels * pricePerPixel; return (paintedPixels, _reward, canvas.isAddressPaid[_address]); } /** * Withdraws reward for contributing in canvas. Calculating reward has to be triggered * and calculated per canvas. Because of that it is not enough to call function * withdraw(). Caller has to call addRewardToPendingWithdrawals() separately. */ function addRewardToPendingWithdrawals(uint32 _canvasId) external stateOwned(_canvasId) forceOwned(_canvasId) { Canvas storage canvas = _getCanvas(_canvasId); uint32 pixelCount; uint reward; bool isPaid; (pixelCount, reward, isPaid) = calculateReward(_canvasId, msg.sender); require(pixelCount > 0); require(reward > 0); require(!isPaid); canvas.isAddressPaid[msg.sender] = true; addPendingWithdrawal(msg.sender, reward); emit RewardAddedToWithdrawals(_canvasId, msg.sender, reward); } /** * @notice Calculates commission that has been charged for selling the canvas. */ function calculateCommission(uint32 _canvasId) public view stateOwned(_canvasId) returns (uint commission, bool isPaid) { Bid storage bid = bids[_canvasId]; Canvas storage canvas = _getCanvas(_canvasId); return (_calculateCommission(bid.amount), canvas.isCommissionPaid); } /** * @notice Only for the owner of the contract. Adds commission to the owner&#39;s * pending withdrawals. */ function addCommissionToPendingWithdrawals(uint32 _canvasId) external onlyOwner stateOwned(_canvasId) forceOwned(_canvasId) { Canvas storage canvas = _getCanvas(_canvasId); uint commission; bool isPaid; (commission, isPaid) = calculateCommission(_canvasId); require(commission > 0); require(!isPaid); canvas.isCommissionPaid = true; addPendingWithdrawal(owner, commission); emit CommissionAddedToWithdrawals(_canvasId, commission, ACTION_INITIAL_BIDDING); } /** * @notice Returns number of canvases owned by the given address. */ function balanceOf(address _owner) external view returns (uint) { return addressToCount[_owner]; } /** * @notice Only for the owner of the contract. Sets minimum bid amount. */ function setMinimumBidAmount(uint _amount) external onlyOwner { minimumBidAmount = _amount; } function _calculatePricePerPixel(uint _totalPrice) private pure returns (uint) { return (_totalPrice - _calculateCommission(_totalPrice)) / PIXEL_COUNT; } function _calculateCommission(uint _amount) internal pure returns (uint) { return (_amount * COMMISSION) / COMMISSION_DIVIDER; } /** * @dev Slices array from start (inclusive) to end (exclusive). * Doesn&#39;t modify input array. */ function _slice(uint32[] memory _array, uint _start, uint _end) internal pure returns (uint32[]) { require(_start <= _end); if (_start == 0 && _end == _array.length) { return _array; } uint size = _end - _start; uint32[] memory sliced = new uint32[](size); for (uint i = 0; i < size; i++) { sliced[i] = _array[i + _start]; } return sliced; } struct Bid { address bidder; uint amount; } } /** * @dev This contract takes trading our artworks. Trading can happen * if artwork has been initially bought. */ contract CanvasMarket is BiddableCanvas { mapping(uint32 => SellOffer) canvasForSale; mapping(uint32 => BuyOffer) buyOffers; event CanvasOfferedForSale(uint32 indexed canvasId, uint minPrice, address indexed from, address indexed to); event SellOfferCancelled(uint32 indexed canvasId, uint minPrice, address indexed from, address indexed to); event CanvasSold(uint32 indexed canvasId, uint amount, address indexed from, address indexed to); event BuyOfferMade(uint32 indexed canvasId, address indexed buyer, uint amount); event BuyOfferCancelled(uint32 indexed canvasId, address indexed buyer, uint amount); struct SellOffer { bool isForSale; address seller; uint minPrice; address onlySellTo; // specify to sell only to a specific address } struct BuyOffer { bool hasOffer; address buyer; uint amount; } /** * @notice Buy artwork. Artwork has to be put on sale. If buyer has bid before for * that artwork, that bid will be canceled. */ function acceptSellOffer(uint32 _canvasId) external payable stateOwned(_canvasId) forceOwned(_canvasId) { Canvas storage canvas = _getCanvas(_canvasId); SellOffer memory sellOffer = canvasForSale[_canvasId]; require(msg.sender != canvas.owner); //don&#39;t sell for the owner require(sellOffer.isForSale); require(msg.value >= sellOffer.minPrice); require(sellOffer.seller == canvas.owner); //seller is no longer owner require(sellOffer.onlySellTo == 0x0 || sellOffer.onlySellTo == msg.sender); //protect from selling to unintended address uint fee = _calculateCommission(msg.value); uint toTransfer = msg.value - fee; addPendingWithdrawal(sellOffer.seller, toTransfer); addPendingWithdrawal(owner, fee); addressToCount[canvas.owner]--; addressToCount[msg.sender]++; canvas.owner = msg.sender; cancelSellOfferInternal(_canvasId, false); emit CanvasSold(_canvasId, msg.value, sellOffer.seller, msg.sender); emit CommissionAddedToWithdrawals(_canvasId, fee, ACTION_SELL_OFFER_ACCEPTED); //If the buyer have placed buy offer, refund it BuyOffer memory offer = buyOffers[_canvasId]; if (offer.buyer == msg.sender) { buyOffers[_canvasId] = BuyOffer(false, 0x0, 0); if (offer.amount > 0) { //refund offer addPendingWithdrawal(offer.buyer, offer.amount); } } } /** * @notice Offer canvas for sale for a minimal price. * Anybody can buy it for an amount grater or equal to min price. */ function offerCanvasForSale(uint32 _canvasId, uint _minPrice) external { _offerCanvasForSaleInternal(_canvasId, _minPrice, 0x0); } /** * @notice Offer canvas for sale to a given address. Only that address * is allowed to buy canvas for an amount grater or equal * to minimal price. */ function offerCanvasForSaleToAddress(uint32 _canvasId, uint _minPrice, address _receiver) external { _offerCanvasForSaleInternal(_canvasId, _minPrice, _receiver); } /** * @notice Cancels previously made sell offer. Caller has to be an owner * of the canvas. Function will fail if there is no sell offer * for the canvas. */ function cancelSellOffer(uint32 _canvasId) external { cancelSellOfferInternal(_canvasId, true); } /** * @notice Places buy offer for the canvas. It cannot be called by the owner of the canvas. * New offer has to be bigger than existing offer. Returns ethers to the previous * bidder, if any. */ function makeBuyOffer(uint32 _canvasId) external payable stateOwned(_canvasId) forceOwned(_canvasId) { Canvas storage canvas = _getCanvas(_canvasId); BuyOffer storage existing = buyOffers[_canvasId]; require(canvas.owner != msg.sender); require(canvas.owner != 0x0); require(msg.value > existing.amount); if (existing.amount > 0) { //refund previous buy offer. addPendingWithdrawal(existing.buyer, existing.amount); } buyOffers[_canvasId] = BuyOffer(true, msg.sender, msg.value); emit BuyOfferMade(_canvasId, msg.sender, msg.value); } /** * @notice Cancels previously made buy offer. Caller has to be an author * of the offer. */ function cancelBuyOffer(uint32 _canvasId) external stateOwned(_canvasId) forceOwned(_canvasId) { BuyOffer memory offer = buyOffers[_canvasId]; require(offer.buyer == msg.sender); buyOffers[_canvasId] = BuyOffer(false, 0x0, 0); if (offer.amount > 0) { //refund offer addPendingWithdrawal(offer.buyer, offer.amount); } emit BuyOfferCancelled(_canvasId, offer.buyer, offer.amount); } /** * @notice Accepts buy offer for the canvas. Caller has to be the owner * of the canvas. You can specify minimal price, which is the * protection against accidental calls. */ function acceptBuyOffer(uint32 _canvasId, uint _minPrice) external stateOwned(_canvasId) forceOwned(_canvasId) { Canvas storage canvas = _getCanvas(_canvasId); require(canvas.owner == msg.sender); BuyOffer memory offer = buyOffers[_canvasId]; require(offer.hasOffer); require(offer.amount > 0); require(offer.buyer != 0x0); require(offer.amount >= _minPrice); uint fee = _calculateCommission(offer.amount); uint toTransfer = offer.amount - fee; addressToCount[canvas.owner]--; addressToCount[offer.buyer]++; canvas.owner = offer.buyer; addPendingWithdrawal(msg.sender, toTransfer); addPendingWithdrawal(owner, fee); buyOffers[_canvasId] = BuyOffer(false, 0x0, 0); canvasForSale[_canvasId] = SellOffer(false, 0x0, 0, 0x0); emit CanvasSold(_canvasId, offer.amount, msg.sender, offer.buyer); emit CommissionAddedToWithdrawals(_canvasId, fee, ACTION_BUY_OFFER_ACCEPTED); } /** * @notice Returns current buy offer for the canvas. */ function getCurrentBuyOffer(uint32 _canvasId) external view returns (bool hasOffer, address buyer, uint amount) { BuyOffer storage offer = buyOffers[_canvasId]; return (offer.hasOffer, offer.buyer, offer.amount); } /** * @notice Returns current sell offer for the canvas. */ function getCurrentSellOffer(uint32 _canvasId) external view returns (bool isForSale, address seller, uint minPrice, address onlySellTo) { SellOffer storage offer = canvasForSale[_canvasId]; return (offer.isForSale, offer.seller, offer.minPrice, offer.onlySellTo); } function _offerCanvasForSaleInternal(uint32 _canvasId, uint _minPrice, address _receiver) private stateOwned(_canvasId) forceOwned(_canvasId) { Canvas storage canvas = _getCanvas(_canvasId); require(canvas.owner == msg.sender); require(_receiver != canvas.owner); canvasForSale[_canvasId] = SellOffer(true, msg.sender, _minPrice, _receiver); emit CanvasOfferedForSale(_canvasId, _minPrice, msg.sender, _receiver); } function cancelSellOfferInternal(uint32 _canvasId, bool emitEvent) private stateOwned(_canvasId) forceOwned(_canvasId) { Canvas storage canvas = _getCanvas(_canvasId); SellOffer memory oldOffer = canvasForSale[_canvasId]; require(canvas.owner == msg.sender); require(oldOffer.isForSale); //don&#39;t allow to cancel if there is no offer canvasForSale[_canvasId] = SellOffer(false, msg.sender, 0, 0x0); if (emitEvent) { emit SellOfferCancelled(_canvasId, oldOffer.minPrice, oldOffer.seller, oldOffer.onlySellTo); } } } /** * CryptoCanvas Terms of Use * * 1. Intro * * CryptoCanvas is a set of collectible artworks (“Canvas”) created by the CryptoCanvas community with proof of ownership stored on the Ethereum blockchain. * * This agreement does a few things. First, it passes copyright ownership of a Canvas from the Canvas Authors to the first Canvas Owner. The first Canvas Owner is then obligated to pass on the copyright ownership along with the Canvas to the next owner, and so on forever, such that each owner of a Canvas is also the copyright owner. Second, it requires each Canvas Owner to allow certain uses of their Canvas image. Third, it limits the rights of Canvas owners to sue The Mindhouse and the prior owners of the Canvas. * * Canvases of CryptoCanvas are not an investment. They are experimental digital art. * * PLEASE READ THESE TERMS CAREFULLY BEFORE USING THE APP, THE SMART CONTRACTS, OR THE SITE. BY USING THE APP, THE SMART CONTRACTS, THE SITE, OR ANY PART OF THEM YOU ARE CONFIRMING THAT YOU UNDERSTAND AND AGREE TO BE BOUND BY ALL OF THESE TERMS. IF YOU ARE ACCEPTING THESE TERMS ON BEHALF OF A COMPANY OR OTHER LEGAL ENTITY, YOU REPRESENT THAT YOU HAVE THE LEGAL AUTHORITY TO ACCEPT THESE TERMS ON THAT ENTITY’S BEHALF, IN WHICH CASE “YOU” WILL MEAN THAT ENTITY. IF YOU DO NOT HAVE SUCH AUTHORITY, OR IF YOU DO NOT ACCEPT ALL OF THESE TERMS, THEN WE ARE UNWILLING TO MAKE THE APP, THE SMART CONTRACTS, OR THE SITE AVAILABLE TO YOU. IF YOU DO NOT AGREE TO THESE TERMS, YOU MAY NOT ACCESS OR USE THE APP, THE SMART CONTRACTS, OR THE SITE. * * 2. Definitions * * “Smart Contract” refers to this smart contract. * * “Canvas” means a collectible artwork created by the CryptoCanvas community with information about the color and author of each pixel of the Canvas, and proof of ownership stored in the Smart Contract. The Canvas is considered finished when all the pixels of the Canvas have their color set. Specifically, the Canvas is considered finished when its “state” field in the Smart Contract equals to STATE_INITIAL_BIDDING or STATE_OWNED constant. * * “Canvas Author” means the person who painted at least one final pixel of the finished Canvas by sending a transaction to the Smart Contract. A person whose pixel has been painted over by another person loses rights to that pixel. Specifically, Canvas Author means the person with the private key for at least one address in the “painter” field of the “pixels” field of the applicable Canvas in the Smart Contract. * * “Canvas Owner” means the person that can cryptographically prove ownership of the applicable Canvas. Specifically, Canvas Owner means the person with the private key for the address in the “owner” field of the applicable Canvas in the Smart Contract. The person is the Canvas Owner only after the Initial Bidding phase is finished, that is when the field “state” of the applicable Canvas equals to the STATE_OWNED constant. * * “Initial Bidding” means the state of the Canvas when each of its pixels has been set by Canvas Authors but it does not have the Canvas Owner yet. In this phase any user can claim the ownership of the Canvas by sending a transaction to the Smart Contract (a “Bid”). Other users have 48 hours from the time of making the first Bid on the Canvas to submit their own Bids. After that time, the user who sent the highest Bid becomes the sole Canvas Owner of the applicable Canvas. Users who placed Bids with lower amounts are able to withdraw their Bid amount from their Account Balance. * * “Account Balance” means the value stored in the Smart Contract assigned to an address. The Account Balance can be withdrawn by the person with the private key for the applicable address by sending a transaction to the Smart Contract. Account Balance consists of Rewards for painting, Bids from Initial Bidding which have been overbid, cancelled offers to buy a Canvas and profits from selling a Canvas. * * “The Mindhouse”, “we” or “us” is the group of developers who created and published the CryptoCanvas Smart Contract. * * “The App” means collectively the Smart Contract and the website created by The Mindhouse to interact with the Smart Contract. * * 3. Intellectual Property * * A. First Assignment * The Canvas Authors of the applicable Canvas hereby assign all copyright ownership in the Canvas to the Canvas Owner. In exchange for this copyright ownership, the Canvas Owner agrees to the terms below. * * B. Later Assignments * When the Canvas Owner transfers the Canvas to a new owner, the Canvas Owner hereby agrees to assign all copyright ownership in the Canvas to the new owner of the Canvas. In exchange for these rights, the new owner shall agree to become the Canvas Owner, and shall agree to be subject to this Terms of Use. * * C. No Other Assignments. * The Canvas Owner shall not assign or license the copyright except as set forth in the “Later Assignments” section above. * * D. Third Party Permissions. * The Canvas Owner agrees to allow CryptoCanvas fans to make non-commercial Use of images of the Canvas to discuss CryptoCanvas, digital collectibles and related matters. “Use” means to reproduce, display, transmit, and distribute images of the Canvas. This permission excludes the right to print the Canvas onto physical copies (including, for example, shirts and posters). * * 4. Fees and Payment * * A. If you choose to paint, make a bid or trade any Canvas of CryptoCanvas any financial transactions that you engage in will be conducted solely through the Ethereum network via MetaMask. We will have no insight into or control over these payments or transactions, nor do we have the ability to reverse any transactions. With that in mind, we will have no liability to you or to any third party for any claims or damages that may arise as a result of any transactions that you engage in via the App, or using the Smart Contracts, or any other transactions that you conduct via the Ethereum network or MetaMask. * * B. Ethereum requires the payment of a transaction fee (a “Gas Fee”) for every transaction that occurs on the Ethereum network. The Gas Fee funds the network of computers that run the decentralized Ethereum network. This means that you will need to pay a Gas Fee for each transaction that occurs via the App. * * C. In addition to the Gas Fee, each time you sell a Canvas to another user of the App, you authorize us to collect a commission of 3.9% of the total value of that transaction (a “Commission”). You acknowledge and agree that the Commission will be transferred to us through the Ethereum network as part of the payment. * * D. If you are the Canvas Author you are eligible to receive a reward for painting a Canvas (a “Reward”) after the Initial Bidding phase is completed. You acknowledge and agree that the Reward for the Canvas Author will be calculated by dividing the value of the highest Bid decreased by our commision of 3.9% of the total value of the Bid, by the total number of pixels of the Canvas and multiplied by the number of pixels of the Canvas that have been painted by the applicable Canvas Author. You acknowledge and agree that in order to withdraw the Reward you first need to add the Reward to your Account Balance by sending a transaction to the Smart Contract. * * 5. Disclaimers * * A. YOU EXPRESSLY UNDERSTAND AND AGREE THAT YOUR ACCESS TO AND USE OF THE APP IS AT YOUR SOLE RISK, AND THAT THE APP IS PROVIDED "AS IS" AND "AS AVAILABLE" WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR IMPLIED. TO THE FULLEST EXTENT PERMISSIBLE PURSUANT TO APPLICABLE LAW, WE, OUR SUBSIDIARIES, AFFILIATES, AND LICENSORS MAKE NO EXPRESS WARRANTIES AND HEREBY DISCLAIM ALL IMPLIED WARRANTIES REGARDING THE APP AND ANY PART OF IT (INCLUDING, WITHOUT LIMITATION, THE SITE, ANY SMART CONTRACT, OR ANY EXTERNAL WEBSITES), INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, CORRECTNESS, ACCURACY, OR RELIABILITY. WITHOUT LIMITING THE GENERALITY OF THE FOREGOING, WE, OUR SUBSIDIARIES, AFFILIATES, AND LICENSORS DO NOT REPRESENT OR WARRANT TO YOU THAT: (I) YOUR ACCESS TO OR USE OF THE APP WILL MEET YOUR REQUIREMENTS, (II) YOUR ACCESS TO OR USE OF THE APP WILL BE UNINTERRUPTED, TIMELY, SECURE OR FREE FROM ERROR, (III) USAGE DATA PROVIDED THROUGH THE APP WILL BE ACCURATE, (III) THE APP OR ANY CONTENT, SERVICES, OR FEATURES MADE AVAILABLE ON OR THROUGH THE APP ARE FREE OF VIRUSES OR OTHER HARMFUL COMPONENTS, OR (IV) THAT ANY DATA THAT YOU DISCLOSE WHEN YOU USE THE APP WILL BE SECURE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES IN CONTRACTS WITH CONSUMERS, SO SOME OR ALL OF THE ABOVE EXCLUSIONS MAY NOT APPLY TO YOU. * * B. YOU ACCEPT THE INHERENT SECURITY RISKS OF PROVIDING INFORMATION AND DEALING ONLINE OVER THE INTERNET, AND AGREE THAT WE HAVE NO LIABILITY OR RESPONSIBILITY FOR ANY BREACH OF SECURITY UNLESS IT IS DUE TO OUR GROSS NEGLIGENCE. * * C. WE WILL NOT BE RESPONSIBLE OR LIABLE TO YOU FOR ANY LOSSES YOU INCUR AS THE RESULT OF YOUR USE OF THE ETHEREUM NETWORK OR THE METAMASK ELECTRONIC WALLET, INCLUDING BUT NOT LIMITED TO ANY LOSSES, DAMAGES OR CLAIMS ARISING FROM: (A) USER ERROR, SUCH AS FORGOTTEN PASSWORDS OR INCORRECTLY CONSTRUED SMART CONTRACTS OR OTHER TRANSACTIONS; (B) SERVER FAILURE OR DATA LOSS; (C) CORRUPTED WALLET FILES; (D) UNAUTHORIZED ACCESS OR ACTIVITIES BY THIRD PARTIES, INCLUDING BUT NOT LIMITED TO THE USE OF VIRUSES, PHISHING, BRUTEFORCING OR OTHER MEANS OF ATTACK AGAINST THE APP, ETHEREUM NETWORK, OR THE METAMASK ELECTRONIC WALLET. * * D. THE CANVASES OF CRYPTOCANVAS ARE INTANGIBLE DIGITAL ASSETS THAT EXIST ONLY BY VIRTUE OF THE OWNERSHIP RECORD MAINTAINED IN THE ETHEREUM NETWORK. ALL SMART CONTRACTS ARE CONDUCTED AND OCCUR ON THE DECENTRALIZED LEDGER WITHIN THE ETHEREUM PLATFORM. WE HAVE NO CONTROL OVER AND MAKE NO GUARANTEES OR PROMISES WITH RESPECT TO SMART CONTRACTS. * * E. THE MINDHOUSE IS NOT RESPONSIBLE FOR LOSSES DUE TO BLOCKCHAINS OR ANY OTHER FEATURES OF THE ETHEREUM NETWORK OR THE METAMASK ELECTRONIC WALLET, INCLUDING BUT NOT LIMITED TO LATE REPORT BY DEVELOPERS OR REPRESENTATIVES (OR NO REPORT AT ALL) OF ANY ISSUES WITH THE BLOCKCHAIN SUPPORTING THE ETHEREUM NETWORK, INCLUDING FORKS, TECHNICAL NODE ISSUES, OR ANY OTHER ISSUES HAVING FUND LOSSES AS A RESULT. * * 6. Limitation of Liability * YOU UNDERSTAND AND AGREE THAT WE, OUR SUBSIDIARIES, AFFILIATES, AND LICENSORS WILL NOT BE LIABLE TO YOU OR TO ANY THIRD PARTY FOR ANY CONSEQUENTIAL, INCIDENTAL, INDIRECT, EXEMPLARY, SPECIAL, PUNITIVE, OR ENHANCED DAMAGES, OR FOR ANY LOSS OF ACTUAL OR ANTICIPATED PROFITS (REGARDLESS OF HOW THESE ARE CLASSIFIED AS DAMAGES), WHETHER ARISING OUT OF BREACH OF CONTRACT, TORT (INCLUDING NEGLIGENCE), OR OTHERWISE, REGARDLESS OF WHETHER SUCH DAMAGE WAS FORESEEABLE AND WHETHER EITHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * * @dev Contract to be placed in blockchain. Contains utility methods. */ contract CryptoArt is CanvasMarket { function getCanvasInfo(uint32 _canvasId) external view returns ( uint32 id, uint32 paintedPixels, uint8 canvasState, uint initialBiddingFinishTime, address owner ) { Canvas storage canvas = _getCanvas(_canvasId); return (_canvasId, canvas.paintedPixelsCount, getCanvasState(_canvasId), canvas.initialBiddingFinishTime, canvas.owner); } function getCanvasByOwner(address _owner) external view returns (uint32[]) { uint32[] memory result = new uint32[](canvases.length); uint currentIndex = 0; for (uint32 i = 0; i < canvases.length; i++) { if (getCanvasState(i) == STATE_OWNED) { Canvas storage canvas = _getCanvas(i); if (canvas.owner == _owner) { result[currentIndex] = i; currentIndex++; } } } return _slice(result, 0, currentIndex); } /** * @notice Returns array of canvas&#39;s ids. Returned canvases have sell offer. * If includePrivateOffers is true, includes offers that are targeted * only to one specified address. */ function getCanvasesWithSellOffer(bool includePrivateOffers) external view returns (uint32[]) { uint32[] memory result = new uint32[](canvases.length); uint currentIndex = 0; for (uint32 i = 0; i < canvases.length; i++) { SellOffer storage offer = canvasForSale[i]; if (offer.isForSale && (includePrivateOffers || offer.onlySellTo == 0x0)) { result[currentIndex] = i; currentIndex++; } } return _slice(result, 0, currentIndex); } /** * @notice Returns array of all the owners of all of pixels. If some pixel hasn&#39;t * been painted yet, 0x0 address will be returned. */ function getCanvasPainters(uint32 _canvasId) external view returns (address[]) { Canvas storage canvas = _getCanvas(_canvasId); address[] memory result = new address[](PIXEL_COUNT); for (uint32 i = 0; i < PIXEL_COUNT; i++) { result[i] = canvas.pixels[i].painter; } return result; } }
* @notice Returns last bid for canvas. If the initial bidding has been already finished that will be winning offer./
function getLastBidForCanvas(uint32 _canvasId) external view returns (uint32 canvasId, address bidder, uint amount, uint finishTime) { Bid storage bid = bids[_canvasId]; Canvas storage canvas = _getCanvas(_canvasId); return (_canvasId, bid.bidder, bid.amount, canvas.initialBiddingFinishTime); }
7,847,839
[ 1, 1356, 1142, 9949, 364, 5953, 18, 971, 326, 2172, 324, 1873, 310, 711, 2118, 6647, 1818, 6708, 716, 903, 506, 5657, 2093, 10067, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7595, 17763, 1290, 12971, 12, 11890, 1578, 389, 15424, 548, 13, 3903, 1476, 1135, 261, 11890, 1578, 5953, 548, 16, 1758, 9949, 765, 16, 2254, 3844, 16, 2254, 4076, 950, 13, 288, 203, 3639, 605, 350, 2502, 9949, 273, 30534, 63, 67, 15424, 548, 15533, 203, 3639, 20966, 2502, 5953, 273, 389, 588, 12971, 24899, 15424, 548, 1769, 203, 203, 3639, 327, 261, 67, 15424, 548, 16, 9949, 18, 19773, 765, 16, 9949, 18, 8949, 16, 5953, 18, 6769, 38, 1873, 310, 11641, 950, 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 ]
pragma solidity ^0.4.18; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title 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 Hive is ERC20 { using SafeMath for uint; string public constant name = "UHIVE"; string public constant symbol = "HVE"; uint256 public constant decimals = 18; uint256 _totalSupply = 80000000000 * (10**decimals); mapping (address => bool) public frozenAccount; event FrozenFunds(address target, bool frozen); // Balances for each account mapping(address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) allowed; // Owner of this contract address public owner; // Functions with this modifier can only be executed by the owner modifier onlyOwner() { require(msg.sender == owner); _; } function changeOwner(address _newOwner) onlyOwner public { require(_newOwner != address(0)); owner = _newOwner; } function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } function isFrozenAccount(address _addr) public constant returns (bool) { return frozenAccount[_addr]; } function destroyCoins(address addressToDestroy, uint256 amount) onlyOwner public { require(addressToDestroy != address(0)); require(amount > 0); require(amount <= balances[addressToDestroy]); balances[addressToDestroy] -= amount; _totalSupply -= amount; } // Constructor function Hive() public { owner = msg.sender; balances[owner] = _totalSupply; } function totalSupply() public constant returns (uint256 supply) { supply = _totalSupply; } // What is the balance of a particular account? function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } // Transfer the balance from owner's account to another account function transfer(address _to, uint256 _value) public returns (bool success) { if (_to != address(0) && isFrozenAccount(msg.sender) == false && balances[msg.sender] >= _value && _value > 0 && balances[_to].add(_value) > balances[_to]) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } else { return false; } } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom(address _from,address _to, uint256 _value) public returns (bool success) { if (_to != address(0) && isFrozenAccount(_from) == false && balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0 && balances[_to].add(_value) > balances[_to]) { balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); return true; } else { return false; } } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract UhiveVest { using SafeMath for uint256; // The token being sold Hive public token; // Owner of this contract address public owner; uint256 public releaseDate; // Functions with this modifier can only be executed when the vesting period elapses modifier onlyWhenReleased { require(now >= releaseDate); _; } // Functions with this modifier can only be executed by the owner modifier onlyOwner() { require(msg.sender == owner); _; } function UhiveVest(Hive _token, uint256 _releaseDate) public { token = _token; owner = msg.sender; releaseDate = _releaseDate; } function () external payable { _forwardFunds(); } function _forwardFunds() private { owner.transfer(msg.value); } /** * Event for token transfer 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 TokenTransfer(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //Transfer tokens to a specified address, works only after vesting period elapses function forwardTokens(address _beneficiary, uint256 totalTokens) onlyOwner onlyWhenReleased public { _preValidateTokenTransfer(_beneficiary, totalTokens); _deliverTokens(_beneficiary, totalTokens); } //Withdraw tokens to owner wallet, works only after vesting period elapses function withdrawTokens() onlyOwner onlyWhenReleased public { uint256 unsold = token.balanceOf(this); token.transfer(owner, unsold); } //Change the owner wallet address function changeOwner(address _newOwner) onlyOwner public { require(_newOwner != address(0)); owner = _newOwner; } //Self-destruct the contract, contract cannot be destroyed until the vesting period is over. function terminate() public onlyOwner onlyWhenReleased { selfdestruct(owner); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- //Assertain the validity of the transfer function _preValidateTokenTransfer(address _beneficiary, uint256 _tokenAmount) internal pure { require(_beneficiary != address(0)); require(_tokenAmount > 0); } //Forward the tokens from the contract to the beneficiary function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); TokenTransfer(msg.sender, _beneficiary, 0, _tokenAmount); } }
Withdraw tokens to owner wallet, works only after vesting period elapses
function withdrawTokens() onlyOwner onlyWhenReleased public { uint256 unsold = token.balanceOf(this); token.transfer(owner, unsold); }
252,497
[ 1, 1190, 9446, 2430, 358, 3410, 9230, 16, 6330, 1338, 1839, 331, 10100, 3879, 415, 30996, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 5157, 1435, 1338, 5541, 1338, 9434, 26363, 1071, 288, 377, 203, 3639, 2254, 5034, 16804, 1673, 273, 1147, 18, 12296, 951, 12, 2211, 1769, 203, 3639, 1147, 18, 13866, 12, 8443, 16, 16804, 1673, 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 ]
pragma solidity ^0.4.16; interface CCCRCoin { function transfer(address receiver, uint amount); } library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract CCCRSale is Pausable { using SafeMath for uint256; address public investWallet = 0xbb2efFab932a4c2f77Fc1617C1a563738D71B0a7; CCCRCoin public tokenReward; uint256 public tokenPrice = 856; // 1ETH (856$) / 1$ uint256 zeroAmount = 10000000000; // 10 zero uint256 startline = 1510736400; // 15.11.17 12:00 uint256 public minCap = 300000000000000; uint256 public totalRaised = 207008997355300; function CCCRSale(address _tokenReward) { tokenReward = CCCRCoin(_tokenReward); } function () whenNotPaused payable { buy(msg.sender, msg.value); } function getRate() constant internal returns (uint256) { if (block.timestamp < startline + 19 days) return tokenPrice.mul(138).div(100); // 15.11.17-4.12.17 38% else if (block.timestamp <= startline + 46 days) return tokenPrice.mul(123).div(100); // 4.12.17-31.12.17 23% else if (block.timestamp <= startline + 60 days) return tokenPrice.mul(115).div(100); // 1.01.18-14.01.18 15% else if (block.timestamp <= startline + 74 days) return tokenPrice.mul(109).div(100); // 15.01.18-28.01.18 9% return tokenPrice; // 29.01.18-31.03.18 } function buy(address buyer, uint256 _amount) whenNotPaused payable { require(buyer != address(0)); require(msg.value != 0); uint256 amount = _amount.div(zeroAmount); uint256 tokens = amount.mul(getRate()); tokenReward.transfer(buyer, tokens); investWallet.transfer(this.balance); totalRaised = totalRaised.add(tokens); if (totalRaised >= minCap) { paused = true; } } function updatePrice(uint256 _tokenPrice) external onlyOwner { tokenPrice = _tokenPrice; } function transferTokens(uint256 _tokens) external onlyOwner { tokenReward.transfer(owner, _tokens); } function airdrop(address[] _array1, uint256[] _array2) external onlyOwner { address[] memory arrayAddress = _array1; uint256[] memory arrayAmount = _array2; uint256 arrayLength = arrayAddress.length.sub(1); uint256 i = 0; while (i <= arrayLength) { tokenReward.transfer(arrayAddress[i], arrayAmount[i]); i = i.add(1); } } }
15.11.17-4.12.17 38%
if (block.timestamp < startline + 19 days) return tokenPrice.mul(138).div(100);
10,033,945
[ 1, 3600, 18, 2499, 18, 4033, 17, 24, 18, 2138, 18, 4033, 18012, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 309, 1377, 261, 2629, 18, 5508, 411, 787, 1369, 397, 5342, 4681, 13, 327, 1147, 5147, 18, 16411, 12, 26645, 2934, 2892, 12, 6625, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "../libs/Ownable.sol"; import "./ERC20ForwarderStorage.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/IFeeManager.sol"; import "./BiconomyForwarder.sol"; import "../interfaces/IERC20Permit.sol"; /** * @title ERC20 Forwarder * * @notice A contract for dApps to coordinate meta transactions paid for with ERC20 transfers * @notice This contract is upgradeable and using using unstructured proxy pattern. * https://blog.openzeppelin.com/proxy-patterns/ * Users always interact with Proxy contract (storage layer) - ERC20ForwarderProxy.sol * @dev Inherits the ERC20ForwarderRequest struct from Storage contract (using same storage contract inherited by Proxy to avoid storage collisions) - essential for compatibility with The BiconomyForwarder * @dev Tx Flow : calls BiconomyForwarder to handle forwarding, call _transferHandler() to charge fee after * */ contract ERC20Forwarder is Ownable, ERC20ForwarderStorage{ using SafeMath for uint256; bool internal initialized; constructor( address _owner ) public Ownable(_owner){ require(_owner != address(0), "Owner Address cannot be 0"); } /** * @dev sets contract variables * * @param _feeReceiver : address that will receive fees charged in ERC20 tokens * @param _feeManager : the address of the contract that controls the charging of fees * @param _forwarder : the address of the BiconomyForwarder contract * */ function initialize( address _feeReceiver, address _feeManager, address payable _forwarder ) public { require(!initialized, "ERC20 Forwarder: contract is already initialized"); require( _feeReceiver != address(0), "ERC20Forwarder: new fee receiver is the zero address" ); require( _feeManager != address(0), "ERC20Forwarder: new fee manager is the zero address" ); require( _forwarder != address(0), "ERC20Forwarder: new forwarder is the zero address" ); initialized = true; feeReceiver = _feeReceiver; feeManager = _feeManager; forwarder = _forwarder; } function setOracleAggregator(address oa) external onlyOwner{ require( oa != address(0), "ERC20Forwarder: new oracle aggregator can not be a zero address" ); oracleAggregator = oa; emit OracleAggregatorChanged(oracleAggregator, msg.sender); } function setTrustedForwarder(address payable _forwarder) external onlyOwner { require( _forwarder != address(0), "ERC20Forwarder: new trusted forwarder can not be a zero address" ); forwarder = _forwarder; emit TrustedForwarderChanged(forwarder, msg.sender); } /** * @dev enable dApps to change fee receiver addresses, e.g. for rotating keys/security purposes * @param _feeReceiver : address that will receive fees charged in ERC20 tokens */ function setFeeReceiver(address _feeReceiver) external onlyOwner{ require( _feeReceiver != address(0), "ERC20Forwarder: new fee receiver can not be a zero address" ); feeReceiver = _feeReceiver; } /** * @dev enable dApps to change the contract that manages fee collection logic * @param _feeManager : the address of the contract that controls the charging of fees */ function setFeeManager(address _feeManager) external onlyOwner{ require( _feeManager != address(0), "ERC20Forwarder: new fee manager can not be a zero address" ); feeManager = _feeManager; } function setBaseGas(uint128 gas) external onlyOwner{ baseGas = gas; emit BaseGasChanged(baseGas,msg.sender); } function setGasRefund(uint128 refund) external onlyOwner{ gasRefund = refund; emit GasRefundChanged(gasRefund,msg.sender); } function setGasTokenForwarderBaseGas(uint128 gas) external onlyOwner{ gasTokenForwarderBaseGas = gas; emit GasTokenForwarderBaseGasChanged(gasTokenForwarderBaseGas,msg.sender); } /** * Designed to enable the community to track change in storage variable forwarder which is used * as a trusted forwarder contract where signature verifiction and replay attack prevention schemes are * deployed. */ event TrustedForwarderChanged(address indexed newForwarderAddress, address indexed actor); /** * Designed to enable the community to track change in storage variable oracleAggregator which is used * as a oracle aggregator contract where different feeds are aggregated */ event OracleAggregatorChanged(address indexed newOracleAggregatorAddress, address indexed actor); /* Designed to enable the community to track change in storage variable baseGas which is used for charge calcuations Unlikely to change */ event BaseGasChanged(uint128 newBaseGas, address indexed actor); /* Designed to enable the community to track change in storage variable transfer handler gas for particular ERC20 token which is used for charge calculations Only likely to change to offset the charged fee */ event TransferHandlerGasChanged(address indexed tokenAddress, address indexed actor, uint256 indexed newGas); /* Designed to enable the community to track change in refundGas which is used to benefit users when gas tokens are burned Likely to change in the event of offsetting Biconomy's cost OR when new gas tokens are used */ event GasRefundChanged(uint128 newGasRefund, address indexed actor); /* Designed to enable the community to track change in gas token forwarder base gas which is Biconomy's cost when gas tokens are burned for refund Likely to change in the event of offsetting Biconomy's cost OR when new gas token forwarder is used */ event GasTokenForwarderBaseGasChanged(uint128 newGasTokenForwarderBaseGas, address indexed actor); /** * @dev change amount of excess gas charged for _transferHandler * NOT INTENTED TO BE CALLED : may need to be called if : * - new feeManager consumes more/less gas * - token contract is upgraded to consume less gas * - etc */ /// @param _transferHandlerGas : max amount of gas the function _transferHandler is expected to use function setTransferHandlerGas(address token, uint256 _transferHandlerGas) external onlyOwner{ require( token != address(0), "token cannot be zero" ); transferHandlerGas[token] = _transferHandlerGas; emit TransferHandlerGasChanged(token,msg.sender,_transferHandlerGas); } function setSafeTransferRequired(address token, bool _safeTransferRequired) external onlyOwner{ require( token != address(0), "token cannot be zero" ); safeTransferRequired[token] = _safeTransferRequired; } /** * @dev calls the getNonce function of the BiconomyForwarder * @param from : the user address * @param batchId : the key of the user's batch being queried * @return nonce : the number of transaction made within said batch */ function getNonce(address from, uint256 batchId) external view returns(uint256 nonce){ nonce = BiconomyForwarder(forwarder).getNonce(from,batchId); } /** * @dev * - Keeps track of gas consumed * - Calls BiconomyForwarder.executeEIP712 method using arguments given * - Calls _transferHandler, supplying the gas usage of the executeEIP712 call */ /** * @param req : the request being forwarded * @param domainSeparator : the domain separator presented to the user when signing * @param sig : the signature generated by the user's wallet * @return success : false if call fails. true otherwise * @return ret : any return data from the call */ function executeEIP712( ERC20ForwardRequest calldata req, bytes32 domainSeparator, bytes calldata sig ) external returns (bool success, bytes memory ret){ uint256 initialGas = gasleft(); (success,ret) = BiconomyForwarder(forwarder).executeEIP712(req,domainSeparator,sig); uint256 postGas = gasleft(); uint256 transferHandlerGas = transferHandlerGas[req.token]; uint256 charge = _transferHandler(req,initialGas.add(baseGas).add(transferHandlerGas).sub(postGas)); emit FeeCharged(req.from,charge,req.token); } /** * @dev * - calls permit method on the underlying ERC20 token contract (DAI permit type) with given permit options * - Keeps track of gas consumed * - Calls BiconomyForwarder.executeEIP712 method using arguments given * - Calls _transferHandler, supplying the gas usage of the executeEIP712 call */ /** * @param req : the request being forwarded * @param domainSeparator : the domain separator presented to the user when signing * @param sig : the signature generated by the user's wallet * @param permitOptions : the permit request options for executing permit. Since it is not EIP2612 permit pass permitOptions.value = 0 for this struct. * @return success : false if call fails. true otherwise * @return ret : any return data from the call */ function permitAndExecuteEIP712( ERC20ForwardRequest calldata req, bytes32 domainSeparator, bytes calldata sig, PermitRequest calldata permitOptions ) external returns (bool success, bytes memory ret){ uint256 initialGas = gasleft(); (success,ret) = BiconomyForwarder(forwarder).executeEIP712(req,domainSeparator,sig); //DAI permit IERC20Permit(req.token).permit(permitOptions.holder, permitOptions.spender, permitOptions.nonce, permitOptions.expiry, permitOptions.allowed, permitOptions.v, permitOptions.r, permitOptions.s); uint256 postGas = gasleft(); uint256 transferHandlerGas = transferHandlerGas[req.token]; uint256 charge = _transferHandler(req,initialGas.add(baseGas).add(transferHandlerGas).sub(postGas)); emit FeeCharged(req.from,charge,req.token); } /** * @dev * - calls permit method on the underlying ERC20 token contract (which supports EIP2612 permit) with given permit options * - Keeps track of gas consumed * - Calls BiconomyForwarder.executeEIP712 method using arguments given * - Calls _transferHandler, supplying the gas usage of the executeEIP712 call */ /** * @param req : the request being forwarded * @param domainSeparator : the domain separator presented to the user when signing * @param sig : the signature generated by the user's wallet * @param permitOptions : the permit request options for executing permit. Since it is EIP2612 permit pass permitOptions.allowed = true/false for this struct. * @return success : false if call fails. true otherwise * @return ret : any return data from the call */ function permitEIP2612AndExecuteEIP712( ERC20ForwardRequest calldata req, bytes32 domainSeparator, bytes calldata sig, PermitRequest calldata permitOptions ) external returns (bool success, bytes memory ret){ uint256 initialGas = gasleft(); (success,ret) = BiconomyForwarder(forwarder).executeEIP712(req,domainSeparator,sig); //USDC or any EIP2612 permit IERC20Permit(req.token).permit(permitOptions.holder, permitOptions.spender, permitOptions.value, permitOptions.expiry, permitOptions.v, permitOptions.r, permitOptions.s); uint256 postGas = gasleft(); uint256 transferHandlerGas = transferHandlerGas[req.token]; uint256 charge = _transferHandler(req,initialGas.add(baseGas).add(transferHandlerGas).sub(postGas)); emit FeeCharged(req.from,charge,req.token); } /** * @dev * - Keeps track of gas consumed * - Calls BiconomyForwarder.executeEIP712 method using arguments given * - Calls _transferHandler, supplying the gas usage of the executeEIP712 call * * NOT INTENTED TO BE CALLED : may need to be called by Biconomy Relayers */ /** * @param req : the request being forwarded * @param domainSeparator : the domain separator presented to the user when signing * @param sig : the signature generated by the user's wallet * @param gasTokensBurned : number of gas tokens to be burned in this transaction * @return success : false if call fails. true otherwise * @return ret : any return data from the call */ function executeEIP712WithGasTokens( ERC20ForwardRequest calldata req, bytes32 domainSeparator, bytes calldata sig, uint256 gasTokensBurned ) external returns (bool success, bytes memory ret){ uint256 initialGas = gasleft(); (success,ret) = BiconomyForwarder(forwarder).executeEIP712(req,domainSeparator,sig); uint256 postGas = gasleft(); uint256 transferHandlerGas = transferHandlerGas[req.token]; uint256 charge = _transferHandler(req,initialGas.add(baseGas).add(gasTokenForwarderBaseGas).add(transferHandlerGas).sub(postGas).sub(gasTokensBurned.mul(gasRefund))); emit FeeCharged(req.from,charge,req.token); } /** * @dev * - calls permit method on the underlying ERC20 token contract (DAI permit type) with given permit options * - Keeps track of gas consumed * - Calls BiconomyForwarder.executeEIP712 method using arguments given * - Calls _transferHandler, supplying the gas usage of the executeEIP712 call * * NOT INTENTED TO BE CALLED : may need to be called by Biconomy Relayers */ /** * @param req : the request being forwarded * @param domainSeparator : the domain separator presented to the user when signing * @param sig : the signature generated by the user's wallet * @param gasTokensBurned : number of gas tokens to be burned in this transaction * @param permitOptions : the permit request options for executing permit. Since it is not EIP2612 permit pass permitOptions.value = 0 for this struct. * @return success : false if call fails. true otherwise * @return ret : any return data from the call */ function permitAndExecuteEIP712WithGasTokens( ERC20ForwardRequest calldata req, bytes32 domainSeparator, bytes calldata sig, PermitRequest calldata permitOptions, uint256 gasTokensBurned ) external returns (bool success, bytes memory ret){ uint256 initialGas = gasleft(); (success,ret) = BiconomyForwarder(forwarder).executeEIP712(req,domainSeparator,sig); //DAI Permit IERC20Permit(req.token).permit(permitOptions.holder, permitOptions.spender, permitOptions.nonce, permitOptions.expiry, permitOptions.allowed, permitOptions.v, permitOptions.r, permitOptions.s); uint256 postGas = gasleft(); uint256 transferHandlerGas = transferHandlerGas[req.token]; uint256 charge = _transferHandler(req,initialGas.add(baseGas).add(gasTokenForwarderBaseGas).add(transferHandlerGas).sub(postGas).sub(gasTokensBurned.mul(gasRefund))); emit FeeCharged(req.from,charge,req.token); } /** * @dev * - calls permit method on the underlying ERC20 token contract (which supports EIP2612 permit) with given permit options * - Keeps track of gas consumed * - Calls BiconomyForwarder.executeEIP712 method using arguments given * - Calls _transferHandler, supplying the gas usage of the executeEIP712 call * * NOT INTENTED TO BE CALLED : may need to be called by Biconomy Relayers */ /** * @param req : the request being forwarded * @param domainSeparator : the domain separator presented to the user when signing * @param sig : the signature generated by the user's wallet * @param gasTokensBurned : number of gas tokens to be burned in this transaction * @param permitOptions : the permit request options for executing permit. Since it is EIP2612 permit pass permitOptions.allowed = true/false for this struct. * @return success : false if call fails. true otherwise * @return ret : any return data from the call */ function permitEIP2612AndExecuteEIP712WithGasTokens( ERC20ForwardRequest calldata req, bytes32 domainSeparator, bytes calldata sig, PermitRequest calldata permitOptions, uint256 gasTokensBurned ) external returns (bool success, bytes memory ret){ uint256 initialGas = gasleft(); (success,ret) = BiconomyForwarder(forwarder).executeEIP712(req,domainSeparator,sig); //EIP2612 Permit IERC20Permit(req.token).permit(permitOptions.holder, permitOptions.spender, permitOptions.value, permitOptions.expiry, permitOptions.v, permitOptions.r, permitOptions.s); uint256 postGas = gasleft(); uint256 transferHandlerGas = transferHandlerGas[req.token]; uint256 charge = _transferHandler(req,initialGas.add(baseGas).add(gasTokenForwarderBaseGas).add(transferHandlerGas).sub(postGas).sub(gasTokensBurned.mul(gasRefund))); emit FeeCharged(req.from,charge,req.token); } /** * @dev * - Keeps track of gas consumed * - Calls BiconomyForwarder.executePersonalSign method using arguments given * - Calls _transferHandler, supplying the gas usage of the executePersonalSign call **/ /** * @param req : the request being forwarded * @param sig : the signature generated by the user's wallet * @return success : false if call fails. true otherwise * @return ret : any return data from the call */ function executePersonalSign( ERC20ForwardRequest calldata req, bytes calldata sig ) external returns (bool success, bytes memory ret){ uint256 initialGas = gasleft(); (success,ret) = BiconomyForwarder(forwarder).executePersonalSign(req,sig); uint256 postGas = gasleft(); uint256 transferHandlerGas = transferHandlerGas[req.token]; uint256 charge = _transferHandler(req,initialGas.add(baseGas).add(transferHandlerGas).sub(postGas)); emit FeeCharged(req.from,charge,req.token); } /** * @dev * - Keeps track of gas consumed * - Calls BiconomyForwarder.executePersonalSign method using arguments given * - Calls _transferHandler, supplying the gas usage of the executePersonalSign call * NOT INTENTED TO BE CALLED : may need to be called by Biconomy Relayers **/ /** * @param req : the request being forwarded * @param sig : the signature generated by the user's wallet * @param gasTokensBurned : number of gas tokens to be burned in this transaction * @return success : false if call fails. true otherwise * @return ret : any return data from the call */ function executePersonalSignWithGasTokens( ERC20ForwardRequest calldata req, bytes calldata sig, uint256 gasTokensBurned ) external returns (bool success, bytes memory ret){ uint256 initialGas = gasleft(); (success,ret) = BiconomyForwarder(forwarder).executePersonalSign(req,sig); uint256 postGas = gasleft(); uint256 transferHandlerGas = transferHandlerGas[req.token]; uint256 charge = _transferHandler(req,initialGas.add(baseGas).add(gasTokenForwarderBaseGas).add(transferHandlerGas).sub(postGas).sub(gasTokensBurned.mul(gasRefund))); emit FeeCharged(req.from,charge,req.token); } // Designed to enable capturing token fees charged during the execution event FeeCharged(address indexed from, uint256 indexed charge, address indexed token); /** * @dev * - Verifies if token supplied in request is allowed * - Transfers tokenGasPrice*totalGas*feeMultiplier $req.token, from req.to to feeReceiver **/ /** * @param req : the request being forwarded * @param executionGas : amount of gas used to execute the forwarded request call */ function _transferHandler(ERC20ForwardRequest calldata req,uint256 executionGas) internal returns(uint256 charge){ IFeeManager _feeManager = IFeeManager(feeManager); require(_feeManager.getTokenAllowed(req.token),"TOKEN NOT ALLOWED BY FEE MANAGER"); charge = req.tokenGasPrice.mul(executionGas).mul(_feeManager.getFeeMultiplier(req.from,req.token)).div(10000); if (!safeTransferRequired[req.token]){ require(IERC20(req.token).transferFrom( req.from, feeReceiver, charge)); } else{ SafeERC20.safeTransferFrom(IERC20(req.token), req.from,feeReceiver,charge); } } }
* Designed to enable the community to track change in storage variable oracleAggregator which is used as a oracle aggregator contract where different feeds are aggregated/
event OracleAggregatorChanged(address indexed newOracleAggregatorAddress, address indexed actor);
14,015,571
[ 1, 15478, 329, 358, 4237, 326, 19833, 358, 3298, 2549, 316, 2502, 2190, 20865, 17711, 1492, 353, 1399, 487, 279, 20865, 20762, 6835, 1625, 3775, 27684, 854, 16165, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 28544, 17711, 5033, 12, 2867, 8808, 394, 23601, 17711, 1887, 16, 1758, 8808, 8327, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.8; /** * @title ERC721 Non-Fungible Token Standard, additional minting interface * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Mintable { /** * Unsafely mints a token. * @dev Reverts if `to` is the zero address. * @dev Reverts if `tokenId` has already been minted. * @dev Emits an {IERC721-Transfer} event from the zero address. * @param to Address of the new token owner. * @param tokenId Identifier of the token to mint. */ function mint(address to, uint256 tokenId) external; /** * Unsafely mints a batch of tokens. * @dev Reverts if `to` is the zero address. * @dev Reverts if one of `tokenIds` has already been minted. * @dev Emits an {IERC721-Transfer} event from the zero address for each of `tokenIds`. * @param to Address of the new tokens owner. * @param tokenIds Identifiers of the tokens to mint. */ function batchMint(address to, uint256[] calldata tokenIds) external; /** * Safely mints a token. * @dev Reverts if `to` is the zero address. * @dev Reverts if `tokenId` has already ben minted. * @dev Reverts if `to` is a contract and the call to {IERC721TokenReceiver-onERC721Received} fails or is refused. * @dev Emits an {IERC721-Transfer} event from the zero address. * @param to Address of the new token owner. * @param tokenId Identifier of the token to mint. * @param data Optional data to pass along to the receiver call. */ function safeMint( address to, uint256 tokenId, bytes calldata data ) external; }
* @title ERC721 Non-Fungible Token Standard, additional minting interface/
interface IERC721Mintable { function mint(address to, uint256 tokenId) external; function batchMint(address to, uint256[] calldata tokenIds) external; function safeMint( address to, uint256 tokenId, bytes calldata data ) external; }
12,710,453
[ 1, 654, 39, 27, 5340, 3858, 17, 42, 20651, 1523, 3155, 8263, 16, 3312, 312, 474, 310, 1560, 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, 5831, 467, 654, 39, 27, 5340, 49, 474, 429, 288, 203, 565, 445, 312, 474, 12, 2867, 358, 16, 2254, 5034, 1147, 548, 13, 3903, 31, 203, 203, 565, 445, 2581, 49, 474, 12, 2867, 358, 16, 2254, 5034, 8526, 745, 892, 1147, 2673, 13, 3903, 31, 203, 203, 565, 445, 4183, 49, 474, 12, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 1731, 745, 892, 501, 203, 565, 262, 3903, 31, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./PegStabilityModule.sol"; /// @notice ETH PSM that allows separate pausing of mint and redeem /// by the guardian and governor contract MintRedeemPausePSM is PegStabilityModule { /// @notice boolean switch that indicates whether redemptions are paused bool public redeemPaused; /// @notice event that is emitted when redemptions are paused event RedemptionsPaused(address account); /// @notice event that is emitted when redemptions are unpaused event RedemptionsUnpaused(address account); constructor( OracleParams memory params, uint256 _mintFeeBasisPoints, uint256 _redeemFeeBasisPoints, uint256 _reservesThreshold, uint256 _feiLimitPerSecond, uint256 _mintingBufferCap, IERC20 _underlyingToken, IPCVDeposit _surplusTarget ) PegStabilityModule( params, _mintFeeBasisPoints, _redeemFeeBasisPoints, _reservesThreshold, _feiLimitPerSecond, _mintingBufferCap, _underlyingToken, _surplusTarget ) {} /// @notice modifier that allows execution when redemptions are not paused modifier whileRedemptionsNotPaused { require(!redeemPaused, "EthPSM: Redeem paused"); _; } /// @notice modifier that allows execution when redemptions are paused modifier whileRedemptionsPaused { require(redeemPaused, "EthPSM: Redeem not paused"); _; } /// @notice set secondary pausable methods to paused function pauseRedeem() public isGovernorOrGuardianOrAdmin whileRedemptionsNotPaused { redeemPaused = true; emit RedemptionsPaused(msg.sender); } /// @notice set secondary pausable methods to unpaused function unpauseRedeem() public isGovernorOrGuardianOrAdmin whileRedemptionsPaused { redeemPaused = false; emit RedemptionsUnpaused(msg.sender); } /// @notice override redeem function that allows secondary pausing function redeem( address to, uint256 amountFeiIn, uint256 minAmountOut ) external override nonReentrant whileRedemptionsNotPaused returns (uint256 amountOut) { amountOut = _redeem(to, amountFeiIn, minAmountOut); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./../pcv/PCVDeposit.sol"; import "./../fei/minter/RateLimitedMinter.sol"; import "./IPegStabilityModule.sol"; import "./../refs/OracleRef.sol"; import "../Constants.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; contract PegStabilityModule is IPegStabilityModule, RateLimitedMinter, OracleRef, PCVDeposit, ReentrancyGuard { using Decimal for Decimal.D256; using SafeCast for *; using SafeERC20 for IERC20; /// @notice the fee in basis points for selling asset into FEI uint256 public override mintFeeBasisPoints; /// @notice the fee in basis points for buying the asset for FEI uint256 public override redeemFeeBasisPoints; /// @notice the amount of reserves to be held for redemptions uint256 public override reservesThreshold; /// @notice the PCV deposit target IPCVDeposit public override surplusTarget; /// @notice the token this PSM will exchange for FEI /// This token will be set to WETH9 if the bonding curve accepts eth IERC20 public immutable override underlyingToken; /// @notice the max mint and redeem fee in basis points /// Governance can change this fee uint256 public override MAX_FEE = 300; /// @notice struct for passing constructor parameters related to OracleRef struct OracleParams { address coreAddress; address oracleAddress; address backupOracle; int256 decimalsNormalizer; bool doInvert; } /// @notice constructor /// @param params PSM constructor parameter struct constructor( OracleParams memory params, uint256 _mintFeeBasisPoints, uint256 _redeemFeeBasisPoints, uint256 _reservesThreshold, uint256 _feiLimitPerSecond, uint256 _mintingBufferCap, IERC20 _underlyingToken, IPCVDeposit _surplusTarget ) OracleRef(params.coreAddress, params.oracleAddress, params.backupOracle, params.decimalsNormalizer, params.doInvert) /// rate limited minter passes false as the last param as there can be no partial mints RateLimitedMinter(_feiLimitPerSecond, _mintingBufferCap, false) { underlyingToken = _underlyingToken; _setReservesThreshold(_reservesThreshold); _setMintFee(_mintFeeBasisPoints); _setRedeemFee(_redeemFeeBasisPoints); _setSurplusTarget(_surplusTarget); _setContractAdminRole(keccak256("PSM_ADMIN_ROLE")); } /// @notice withdraw assets from PSM to an external address function withdraw(address to, uint256 amount) external override virtual onlyPCVController { _withdrawERC20(address(underlyingToken), to, amount); } /// @notice set the mint fee vs oracle price in basis point terms function setMintFee(uint256 newMintFeeBasisPoints) external override onlyGovernorOrAdmin { _setMintFee(newMintFeeBasisPoints); } /// @notice set the redemption fee vs oracle price in basis point terms function setRedeemFee(uint256 newRedeemFeeBasisPoints) external override onlyGovernorOrAdmin { _setRedeemFee(newRedeemFeeBasisPoints); } /// @notice set the ideal amount of reserves for the contract to hold for redemptions function setReservesThreshold(uint256 newReservesThreshold) external override onlyGovernorOrAdmin { _setReservesThreshold(newReservesThreshold); } /// @notice set the target for sending surplus reserves function setSurplusTarget(IPCVDeposit newTarget) external override onlyGovernorOrAdmin { _setSurplusTarget(newTarget); } /// @notice set the mint fee vs oracle price in basis point terms function _setMintFee(uint256 newMintFeeBasisPoints) internal { require(newMintFeeBasisPoints <= MAX_FEE, "PegStabilityModule: Mint fee exceeds max fee"); uint256 _oldMintFee = mintFeeBasisPoints; mintFeeBasisPoints = newMintFeeBasisPoints; emit MintFeeUpdate(_oldMintFee, newMintFeeBasisPoints); } /// @notice internal helper function to set the redemption fee function _setRedeemFee(uint256 newRedeemFeeBasisPoints) internal { require(newRedeemFeeBasisPoints <= MAX_FEE, "PegStabilityModule: Redeem fee exceeds max fee"); uint256 _oldRedeemFee = redeemFeeBasisPoints; redeemFeeBasisPoints = newRedeemFeeBasisPoints; emit RedeemFeeUpdate(_oldRedeemFee, newRedeemFeeBasisPoints); } /// @notice helper function to set reserves threshold function _setReservesThreshold(uint256 newReservesThreshold) internal { require(newReservesThreshold > 0, "PegStabilityModule: Invalid new reserves threshold"); uint256 oldReservesThreshold = reservesThreshold; reservesThreshold = newReservesThreshold; emit ReservesThresholdUpdate(oldReservesThreshold, newReservesThreshold); } /// @notice helper function to set the surplus target function _setSurplusTarget(IPCVDeposit newSurplusTarget) internal { require(address(newSurplusTarget) != address(0), "PegStabilityModule: Invalid new surplus target"); IPCVDeposit oldTarget = surplusTarget; surplusTarget = newSurplusTarget; emit SurplusTargetUpdate(oldTarget, newSurplusTarget); } // ----------- Public State Changing API ----------- /// @notice send any surplus reserves to the PCV allocation function allocateSurplus() external override { int256 currentSurplus = reservesSurplus(); require(currentSurplus > 0, "PegStabilityModule: No surplus to allocate"); _allocate(currentSurplus.toUint256()); } /// @notice function to receive ERC20 tokens from external contracts function deposit() external override { int256 currentSurplus = reservesSurplus(); if (currentSurplus > 0) { _allocate(currentSurplus.toUint256()); } } /// @notice internal helper method to redeem fei in exchange for an external asset function _redeem( address to, uint256 amountFeiIn, uint256 minAmountOut ) internal virtual returns(uint256 amountOut) { updateOracle(); amountOut = _getRedeemAmountOut(amountFeiIn); require(amountOut >= minAmountOut, "PegStabilityModule: Redeem not enough out"); IERC20(fei()).safeTransferFrom(msg.sender, address(this), amountFeiIn); _transfer(to, amountOut); emit Redeem(to, amountFeiIn, amountOut); } /// @notice internal helper method to mint fei in exchange for an external asset function _mint( address to, uint256 amountIn, uint256 minAmountOut ) internal virtual returns(uint256 amountFeiOut) { updateOracle(); amountFeiOut = _getMintAmountOut(amountIn); require(amountFeiOut >= minAmountOut, "PegStabilityModule: Mint not enough out"); _transferFrom(msg.sender, address(this), amountIn); uint256 amountFeiToTransfer = Math.min(fei().balanceOf(address(this)), amountFeiOut); uint256 amountFeiToMint = amountFeiOut - amountFeiToTransfer; IERC20(fei()).safeTransfer(to, amountFeiToTransfer); if (amountFeiToMint > 0) { _mintFei(to, amountFeiToMint); } emit Mint(to, amountIn, amountFeiOut); } /// @notice function to redeem FEI for an underlying asset /// We do not burn Fei; this allows the contract's balance of Fei to be used before the buffer is used /// In practice, this helps prevent artificial cycling of mint-burn cycles and prevents a griefing vector. function redeem( address to, uint256 amountFeiIn, uint256 minAmountOut ) external virtual override nonReentrant whenNotPaused returns (uint256 amountOut) { amountOut = _redeem(to, amountFeiIn, minAmountOut); } /// @notice function to buy FEI for an underlying asset /// We first transfer any contract-owned fei, then mint the remaining if necessary function mint( address to, uint256 amountIn, uint256 minAmountOut ) external virtual override nonReentrant whenNotPaused returns (uint256 amountFeiOut) { amountFeiOut = _mint(to, amountIn, minAmountOut); } // ----------- Public View-Only API ---------- /// @notice calculate the amount of FEI out for a given `amountIn` of underlying /// First get oracle price of token /// Then figure out how many dollars that amount in is worth by multiplying price * amount. /// ensure decimals are normalized if on underlying they are not 18 function getMintAmountOut(uint256 amountIn) public override view returns (uint256 amountFeiOut) { amountFeiOut = _getMintAmountOut(amountIn); } /// @notice calculate the amount of underlying out for a given `amountFeiIn` of FEI /// First get oracle price of token /// Then figure out how many dollars that amount in is worth by multiplying price * amount. /// ensure decimals are normalized if on underlying they are not 18 function getRedeemAmountOut(uint256 amountFeiIn) public override view returns (uint256 amountTokenOut) { amountTokenOut = _getRedeemAmountOut(amountFeiIn); } /// @notice the maximum mint amount out function getMaxMintAmountOut() external override view returns (uint256) { return fei().balanceOf(address(this)) + buffer(); } /// @notice a flag for whether the current balance is above (true) or below (false) the reservesThreshold function hasSurplus() external override view returns (bool) { return balance() > reservesThreshold; } /// @notice an integer representing the positive surplus or negative deficit of contract balance vs reservesThreshold function reservesSurplus() public override view returns (int256) { return balance().toInt256() - reservesThreshold.toInt256(); } /// @notice function from PCVDeposit that must be overriden function balance() public view override virtual returns(uint256) { return underlyingToken.balanceOf(address(this)); } /// @notice returns address of token this contracts balance is reported in function balanceReportedIn() external view override returns (address) { return address(underlyingToken); } /// @notice override default behavior of not checking fei balance function resistantBalanceAndFei() public view override returns(uint256, uint256) { return (balance(), feiBalance()); } // ----------- Internal Methods ----------- /// @notice helper function to get mint amount out based on current market prices /// @dev will revert if price is outside of bounds and bounded PSM is being used function _getMintAmountOut(uint256 amountIn) private view returns (uint256 amountFeiOut) { Decimal.D256 memory price = readOracle(); _validatePriceRange(price); Decimal.D256 memory adjustedAmountIn = price.mul(amountIn); amountFeiOut = adjustedAmountIn .mul(Constants.BASIS_POINTS_GRANULARITY - mintFeeBasisPoints) .div(Constants.BASIS_POINTS_GRANULARITY) .asUint256(); } /// @notice helper function to get redeem amount out based on current market prices /// @dev will revert if price is outside of bounds and bounded PSM is being used function _getRedeemAmountOut(uint256 amountFeiIn) private view returns (uint256 amountTokenOut) { Decimal.D256 memory price = readOracle(); _validatePriceRange(price); /// get amount of dollars being provided Decimal.D256 memory adjustedAmountIn = Decimal.from( amountFeiIn * (Constants.BASIS_POINTS_GRANULARITY - redeemFeeBasisPoints) / Constants.BASIS_POINTS_GRANULARITY ); /// now turn the dollars into the underlying token amounts /// dollars / price = how much token to pay out amountTokenOut = adjustedAmountIn.div(price).asUint256(); } /// @notice Allocates a portion of escrowed PCV to a target PCV deposit function _allocate(uint256 amount) internal { _transfer(address(surplusTarget), amount); surplusTarget.deposit(); emit AllocateSurplus(msg.sender, amount); } /// @notice transfer ERC20 token function _transfer(address to, uint256 amount) internal { SafeERC20.safeTransfer(underlyingToken, to, amount); } /// @notice transfer assets from user to this contract function _transferFrom(address from, address to, uint256 amount) internal { SafeERC20.safeTransferFrom(underlyingToken, from, to, amount); } /// @notice mint amount of FEI to the specified user on a rate limit function _mintFei(address to, uint256 amount) internal override(CoreRef, RateLimitedMinter) { super._mintFei(to, amount); } // ----------- Hooks ----------- /// @notice overriden function in the bounded PSM function _validatePriceRange(Decimal.D256 memory price) internal view virtual {} } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../refs/CoreRef.sol"; import "./IPCVDeposit.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /// @title abstract contract for withdrawing ERC-20 tokens using a PCV Controller /// @author Fei Protocol abstract contract PCVDeposit is IPCVDeposit, CoreRef { using SafeERC20 for IERC20; /// @notice withdraw ERC20 from the contract /// @param token address of the ERC20 to send /// @param to address destination of the ERC20 /// @param amount quantity of ERC20 to send function withdrawERC20( address token, address to, uint256 amount ) public virtual override onlyPCVController { _withdrawERC20(token, to, amount); } function _withdrawERC20( address token, address to, uint256 amount ) internal { IERC20(token).safeTransfer(to, amount); emit WithdrawERC20(msg.sender, token, to, amount); } /// @notice withdraw ETH from the contract /// @param to address to send ETH /// @param amountOut amount of ETH to send function withdrawETH(address payable to, uint256 amountOut) external virtual override onlyPCVController { Address.sendValue(to, amountOut); emit WithdrawETH(msg.sender, to, amountOut); } function balance() public view virtual override returns(uint256); function resistantBalanceAndFei() public view virtual override returns(uint256, uint256) { return (balance(), 0); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./ICoreRef.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @title A Reference to Core /// @author Fei Protocol /// @notice defines some modifiers and utilities around interacting with Core abstract contract CoreRef is ICoreRef, Pausable { ICore private _core; /// @notice a role used with a subset of governor permissions for this contract only bytes32 public override CONTRACT_ADMIN_ROLE; /// @notice boolean to check whether or not the contract has been initialized. /// cannot be initialized twice. bool private _initialized; constructor(address coreAddress) { _initialize(coreAddress); } /// @notice CoreRef constructor /// @param coreAddress Fei Core to reference function _initialize(address coreAddress) internal { require(!_initialized, "CoreRef: already initialized"); _initialized = true; _core = ICore(coreAddress); _setContractAdminRole(_core.GOVERN_ROLE()); } modifier ifMinterSelf() { if (_core.isMinter(address(this))) { _; } } modifier onlyMinter() { require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter"); _; } modifier onlyBurner() { require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner"); _; } modifier onlyPCVController() { require( _core.isPCVController(msg.sender), "CoreRef: Caller is not a PCV controller" ); _; } modifier onlyGovernorOrAdmin() { require( _core.isGovernor(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not a governor or contract admin" ); _; } modifier onlyGovernor() { require( _core.isGovernor(msg.sender), "CoreRef: Caller is not a governor" ); _; } modifier onlyGuardianOrGovernor() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender), "CoreRef: Caller is not a guardian or governor" ); _; } modifier isGovernorOrGuardianOrAdmin() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not governor or guardian or admin"); _; } modifier onlyFei() { require(msg.sender == address(fei()), "CoreRef: Caller is not FEI"); _; } /// @notice set new Core reference address /// @param newCore the new core address function setCore(address newCore) external override onlyGovernor { require(newCore != address(0), "CoreRef: zero address"); address oldCore = address(_core); _core = ICore(newCore); emit CoreUpdate(oldCore, newCore); } /// @notice sets a new admin role for this contract function setContractAdminRole(bytes32 newContractAdminRole) external override onlyGovernor { _setContractAdminRole(newContractAdminRole); } /// @notice returns whether a given address has the admin role for this contract function isContractAdmin(address _admin) public view override returns (bool) { return _core.hasRole(CONTRACT_ADMIN_ROLE, _admin); } /// @notice set pausable methods to paused function pause() public override onlyGuardianOrGovernor { _pause(); } /// @notice set pausable methods to unpaused function unpause() public override onlyGuardianOrGovernor { _unpause(); } /// @notice address of the Core contract referenced /// @return ICore implementation address function core() public view override returns (ICore) { return _core; } /// @notice address of the Fei contract referenced by Core /// @return IFei implementation address function fei() public view override returns (IFei) { return _core.fei(); } /// @notice address of the Tribe contract referenced by Core /// @return IERC20 implementation address function tribe() public view override returns (IERC20) { return _core.tribe(); } /// @notice fei balance of contract /// @return fei amount held function feiBalance() public view override returns (uint256) { return fei().balanceOf(address(this)); } /// @notice tribe balance of contract /// @return tribe amount held function tribeBalance() public view override returns (uint256) { return tribe().balanceOf(address(this)); } function _burnFeiHeld() internal { fei().burn(feiBalance()); } function _mintFei(address to, uint256 amount) internal virtual { if (amount != 0) { fei().mint(to, amount); } } function _setContractAdminRole(bytes32 newContractAdminRole) internal { bytes32 oldContractAdminRole = CONTRACT_ADMIN_ROLE; CONTRACT_ADMIN_ROLE = newContractAdminRole; emit ContractAdminRoleUpdate(oldContractAdminRole, newContractAdminRole); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../core/ICore.sol"; /// @title CoreRef interface /// @author Fei Protocol interface ICoreRef { // ----------- Events ----------- event CoreUpdate(address indexed oldCore, address indexed newCore); event ContractAdminRoleUpdate(bytes32 indexed oldContractAdminRole, bytes32 indexed newContractAdminRole); // ----------- Governor only state changing api ----------- function setCore(address newCore) external; function setContractAdminRole(bytes32 newContractAdminRole) external; // ----------- Governor or Guardian only state changing api ----------- function pause() external; function unpause() external; // ----------- Getters ----------- function core() external view returns (ICore); function fei() external view returns (IFei); function tribe() external view returns (IERC20); function feiBalance() external view returns (uint256); function tribeBalance() external view returns (uint256); function CONTRACT_ADMIN_ROLE() external view returns (bytes32); function isContractAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./IPermissions.sol"; import "../fei/IFei.sol"; /// @title Core Interface /// @author Fei Protocol interface ICore is IPermissions { // ----------- Events ----------- event FeiUpdate(address indexed _fei); event TribeUpdate(address indexed _tribe); event GenesisGroupUpdate(address indexed _genesisGroup); event TribeAllocation(address indexed _to, uint256 _amount); event GenesisPeriodComplete(uint256 _timestamp); // ----------- Governor only state changing api ----------- function init() external; // ----------- Governor only state changing api ----------- function setFei(address token) external; function setTribe(address token) external; function allocateTribe(address to, uint256 amount) external; // ----------- Getters ----------- function fei() external view returns (IFei); function tribe() external view returns (IERC20); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./IPermissionsRead.sol"; /// @title Permissions interface /// @author Fei Protocol interface IPermissions is IAccessControl, IPermissionsRead { // ----------- Governor only state changing api ----------- function createRole(bytes32 role, bytes32 adminRole) external; function grantMinter(address minter) external; function grantBurner(address burner) external; function grantPCVController(address pcvController) external; function grantGovernor(address governor) external; function grantGuardian(address guardian) external; function revokeMinter(address minter) external; function revokeBurner(address burner) external; function revokePCVController(address pcvController) external; function revokeGovernor(address governor) external; function revokeGuardian(address guardian) external; // ----------- Revoker only state changing api ----------- function revokeOverride(bytes32 role, address account) external; // ----------- Getters ----------- function GUARDIAN_ROLE() external view returns (bytes32); function GOVERN_ROLE() external view returns (bytes32); function BURNER_ROLE() external view returns (bytes32); function MINTER_ROLE() external view returns (bytes32); function PCV_CONTROLLER_ROLE() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title Permissions Read interface /// @author Fei Protocol interface IPermissionsRead { // ----------- Getters ----------- function isBurner(address _address) external view returns (bool); function isMinter(address _address) external view returns (bool); function isGovernor(address _address) external view returns (bool); function isGuardian(address _address) external view returns (bool); function isPCVController(address _address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title FEI stablecoin interface /// @author Fei Protocol interface IFei is IERC20 { // ----------- Events ----------- event Minting( address indexed _to, address indexed _minter, uint256 _amount ); event Burning( address indexed _to, address indexed _burner, uint256 _amount ); event IncentiveContractUpdate( address indexed _incentivized, address indexed _incentiveContract ); // ----------- State changing api ----------- function burn(uint256 amount) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; // ----------- Burner only state changing api ----------- function burnFrom(address account, uint256 amount) external; // ----------- Minter only state changing api ----------- function mint(address account, uint256 amount) external; // ----------- Governor only state changing api ----------- function setIncentiveContract(address account, address incentive) external; // ----------- Getters ----------- function incentiveContract(address account) external view returns (address); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./IPCVDepositBalances.sol"; /// @title a PCV Deposit interface /// @author Fei Protocol interface IPCVDeposit is IPCVDepositBalances { // ----------- Events ----------- event Deposit(address indexed _from, uint256 _amount); event Withdrawal( address indexed _caller, address indexed _to, uint256 _amount ); event WithdrawERC20( address indexed _caller, address indexed _token, address indexed _to, uint256 _amount ); event WithdrawETH( address indexed _caller, address indexed _to, uint256 _amount ); // ----------- State changing api ----------- function deposit() external; // ----------- PCV Controller only state changing api ----------- function withdraw(address to, uint256 amount) external; function withdrawERC20(address token, address to, uint256 amount) external; function withdrawETH(address payable to, uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title a PCV Deposit interface for only balance getters /// @author Fei Protocol interface IPCVDepositBalances { // ----------- Getters ----------- /// @notice gets the effective balance of "balanceReportedIn" token if the deposit were fully withdrawn function balance() external view returns (uint256); /// @notice gets the token address in which this deposit returns its balance function balanceReportedIn() external view returns (address); /// @notice gets the resistant token balance and protocol owned fei of this deposit function resistantBalanceAndFei() external view returns (uint256, uint256); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../../utils/RateLimited.sol"; /// @title abstract contract for putting a rate limit on how fast a contract can mint FEI /// @author Fei Protocol abstract contract RateLimitedMinter is RateLimited { uint256 private constant MAX_FEI_LIMIT_PER_SECOND = 10_000e18; // 10000 FEI/s or ~860m FEI/day constructor( uint256 _feiLimitPerSecond, uint256 _mintingBufferCap, bool _doPartialMint ) RateLimited(MAX_FEI_LIMIT_PER_SECOND, _feiLimitPerSecond, _mintingBufferCap, _doPartialMint) {} /// @notice override the FEI minting behavior to enforce a rate limit function _mintFei(address to, uint256 amount) internal virtual override { uint256 mintAmount = _depleteBuffer(amount); super._mintFei(to, mintAmount); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../refs/CoreRef.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; /// @title abstract contract for putting a rate limit on how fast a contract can perform an action e.g. Minting /// @author Fei Protocol abstract contract RateLimited is CoreRef { /// @notice maximum rate limit per second governance can set for this contract uint256 public immutable MAX_RATE_LIMIT_PER_SECOND; /// @notice the rate per second for this contract uint256 public rateLimitPerSecond; /// @notice the last time the buffer was used by the contract uint256 public lastBufferUsedTime; /// @notice the cap of the buffer that can be used at once uint256 public bufferCap; /// @notice a flag for whether to allow partial actions to complete if the buffer is less than amount bool public doPartialAction; /// @notice the buffer at the timestamp of lastBufferUsedTime uint256 private _bufferStored; event BufferUsed(uint256 amountUsed, uint256 bufferRemaining); event BufferCapUpdate(uint256 oldBufferCap, uint256 newBufferCap); event RateLimitPerSecondUpdate(uint256 oldRateLimitPerSecond, uint256 newRateLimitPerSecond); constructor(uint256 _maxRateLimitPerSecond, uint256 _rateLimitPerSecond, uint256 _bufferCap, bool _doPartialAction) { lastBufferUsedTime = block.timestamp; _setBufferCap(_bufferCap); _bufferStored = _bufferCap; require(_rateLimitPerSecond <= _maxRateLimitPerSecond, "RateLimited: rateLimitPerSecond too high"); _setRateLimitPerSecond(_rateLimitPerSecond); MAX_RATE_LIMIT_PER_SECOND = _maxRateLimitPerSecond; doPartialAction = _doPartialAction; } /// @notice set the rate limit per second function setRateLimitPerSecond(uint256 newRateLimitPerSecond) external virtual onlyGovernorOrAdmin { require(newRateLimitPerSecond <= MAX_RATE_LIMIT_PER_SECOND, "RateLimited: rateLimitPerSecond too high"); _updateBufferStored(); _setRateLimitPerSecond(newRateLimitPerSecond); } /// @notice set the buffer cap function setBufferCap(uint256 newBufferCap) external virtual onlyGovernorOrAdmin { _setBufferCap(newBufferCap); } /// @notice the amount of action used before hitting limit /// @dev replenishes at rateLimitPerSecond per second up to bufferCap function buffer() public view returns(uint256) { uint256 elapsed = block.timestamp - lastBufferUsedTime; return Math.min(_bufferStored + (rateLimitPerSecond * elapsed), bufferCap); } /** @notice the method that enforces the rate limit. Decreases buffer by "amount". If buffer is <= amount either 1. Does a partial mint by the amount remaining in the buffer or 2. Reverts Depending on whether doPartialAction is true or false */ function _depleteBuffer(uint256 amount) internal returns(uint256) { uint256 newBuffer = buffer(); uint256 usedAmount = amount; if (doPartialAction && usedAmount > newBuffer) { usedAmount = newBuffer; } require(newBuffer != 0, "RateLimited: no rate limit buffer"); require(usedAmount <= newBuffer, "RateLimited: rate limit hit"); _bufferStored = newBuffer - usedAmount; lastBufferUsedTime = block.timestamp; emit BufferUsed(usedAmount, _bufferStored); return usedAmount; } function _setRateLimitPerSecond(uint256 newRateLimitPerSecond) internal { uint256 oldRateLimitPerSecond = rateLimitPerSecond; rateLimitPerSecond = newRateLimitPerSecond; emit RateLimitPerSecondUpdate(oldRateLimitPerSecond, newRateLimitPerSecond); } function _setBufferCap(uint256 newBufferCap) internal { _updateBufferStored(); uint256 oldBufferCap = bufferCap; bufferCap = newBufferCap; emit BufferCapUpdate(oldBufferCap, newBufferCap); } function _resetBuffer() internal { _bufferStored = bufferCap; } function _updateBufferStored() internal { _bufferStored = buffer(); lastBufferUsedTime = block.timestamp; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../pcv/IPCVDeposit.sol"; /** * @title Fei Peg Stability Module * @author Fei Protocol * @notice The Fei PSM is a contract which holds a reserve of assets in order to exchange FEI at $1 of underlying assets with a fee. * `mint()` - buy FEI for $1 of underlying tokens * `redeem()` - sell FEI back for $1 of the same * * The contract has a reservesThreshold() of underlying meant to stand ready for redemptions. Any surplus reserves can be sent into the PCV using `allocateSurplus()` * * The contract is a * PCVDeposit - to track reserves * OracleRef - to determine price of underlying, and * RateLimitedMinter - to stop infinite mints and related issues (but this is in the implementation due to inheritance-linearization difficulties) * * Inspired by MakerDAO PSM, code written without reference */ interface IPegStabilityModule { // ----------- Public State Changing API ----------- /// @notice mint `amountFeiOut` FEI to address `to` for `amountIn` underlying tokens /// @dev see getMintAmountOut() to pre-calculate amount out function mint(address to, uint256 amountIn, uint256 minAmountOut) external returns (uint256 amountFeiOut); /// @notice redeem `amountFeiIn` FEI for `amountOut` underlying tokens and send to address `to` /// @dev see getRedeemAmountOut() to pre-calculate amount out function redeem(address to, uint256 amountFeiIn, uint256 minAmountOut) external returns (uint256 amountOut); /// @notice send any surplus reserves to the PCV allocation function allocateSurplus() external; // ----------- Governor or Admin Only State Changing API ----------- /// @notice set the mint fee vs oracle price in basis point terms function setMintFee(uint256 newMintFeeBasisPoints) external; /// @notice set the redemption fee vs oracle price in basis point terms function setRedeemFee(uint256 newRedeemFeeBasisPoints) external; /// @notice set the ideal amount of reserves for the contract to hold for redemptions function setReservesThreshold(uint256 newReservesThreshold) external; /// @notice set the target for sending surplus reserves function setSurplusTarget(IPCVDeposit newTarget) external; // ----------- Getters ----------- /// @notice calculate the amount of FEI out for a given `amountIn` of underlying function getMintAmountOut(uint256 amountIn) external view returns (uint256 amountFeiOut); /// @notice calculate the amount of underlying out for a given `amountFeiIn` of FEI function getRedeemAmountOut(uint256 amountFeiIn) external view returns (uint256 amountOut); /// @notice the maximum mint amount out function getMaxMintAmountOut() external view returns(uint256); /// @notice a flag for whether the current balance is above (true) or below and equal (false) to the reservesThreshold function hasSurplus() external view returns (bool); /// @notice an integer representing the positive surplus or negative deficit of contract balance vs reservesThreshold function reservesSurplus() external view returns (int256); /// @notice the ideal amount of reserves for the contract to hold for redemptions function reservesThreshold() external view returns (uint256); /// @notice the mint fee vs oracle price in basis point terms function mintFeeBasisPoints() external view returns (uint256); /// @notice the redemption fee vs oracle price in basis point terms function redeemFeeBasisPoints() external view returns (uint256); /// @notice the underlying token exchanged for FEI function underlyingToken() external view returns (IERC20); /// @notice the PCV deposit target to send surplus reserves function surplusTarget() external view returns (IPCVDeposit); /// @notice the max mint and redeem fee in basis points function MAX_FEE() external view returns (uint256); // ----------- Events ----------- /// @notice event emitted when excess PCV is allocated event AllocateSurplus(address indexed caller, uint256 amount); /// @notice event emitted when a new max fee is set event MaxFeeUpdate(uint256 oldMaxFee, uint256 newMaxFee); /// @notice event emitted when a new mint fee is set event MintFeeUpdate(uint256 oldMintFee, uint256 newMintFee); /// @notice event emitted when a new redeem fee is set event RedeemFeeUpdate(uint256 oldRedeemFee, uint256 newRedeemFee); /// @notice event emitted when reservesThreshold is updated event ReservesThresholdUpdate(uint256 oldReservesThreshold, uint256 newReservesThreshold); /// @notice event emitted when surplus target is updated event SurplusTargetUpdate(IPCVDeposit oldTarget, IPCVDeposit newTarget); /// @notice event emitted upon a redemption event Redeem(address to, uint256 amountFeiIn, uint256 amountAssetOut); /// @notice event emitted when fei gets minted event Mint(address to, uint256 amountIn, uint256 amountFeiOut); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./IOracleRef.sol"; import "./CoreRef.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; /// @title Reference to an Oracle /// @author Fei Protocol /// @notice defines some utilities around interacting with the referenced oracle abstract contract OracleRef is IOracleRef, CoreRef { using Decimal for Decimal.D256; using SafeCast for int256; /// @notice the oracle reference by the contract IOracle public override oracle; /// @notice the backup oracle reference by the contract IOracle public override backupOracle; /// @notice number of decimals to scale oracle price by, i.e. multiplying by 10^(decimalsNormalizer) int256 public override decimalsNormalizer; bool public override doInvert; /// @notice OracleRef constructor /// @param _core Fei Core to reference /// @param _oracle oracle to reference /// @param _backupOracle backup oracle to reference /// @param _decimalsNormalizer number of decimals to normalize the oracle feed if necessary /// @param _doInvert invert the oracle price if this flag is on constructor(address _core, address _oracle, address _backupOracle, int256 _decimalsNormalizer, bool _doInvert) CoreRef(_core) { _setOracle(_oracle); if (_backupOracle != address(0) && _backupOracle != _oracle) { _setBackupOracle(_backupOracle); } _setDoInvert(_doInvert); _setDecimalsNormalizer(_decimalsNormalizer); } /// @notice sets the referenced oracle /// @param newOracle the new oracle to reference function setOracle(address newOracle) external override onlyGovernor { _setOracle(newOracle); } /// @notice sets the flag for whether to invert or not /// @param newDoInvert the new flag for whether to invert function setDoInvert(bool newDoInvert) external override onlyGovernor { _setDoInvert(newDoInvert); } /// @notice sets the new decimalsNormalizer /// @param newDecimalsNormalizer the new decimalsNormalizer function setDecimalsNormalizer(int256 newDecimalsNormalizer) external override onlyGovernor { _setDecimalsNormalizer(newDecimalsNormalizer); } /// @notice sets the referenced backup oracle /// @param newBackupOracle the new backup oracle to reference function setBackupOracle(address newBackupOracle) external override onlyGovernorOrAdmin { _setBackupOracle(newBackupOracle); } /// @notice invert a peg price /// @param price the peg price to invert /// @return the inverted peg as a Decimal /// @dev the inverted peg would be X per FEI function invert(Decimal.D256 memory price) public pure override returns (Decimal.D256 memory) { return Decimal.one().div(price); } /// @notice updates the referenced oracle function updateOracle() public override { oracle.update(); } /// @notice the peg price of the referenced oracle /// @return the peg as a Decimal /// @dev the peg is defined as FEI per X with X being ETH, dollars, etc function readOracle() public view override returns (Decimal.D256 memory) { (Decimal.D256 memory _peg, bool valid) = oracle.read(); if (!valid && address(backupOracle) != address(0)) { (_peg, valid) = backupOracle.read(); } require(valid, "OracleRef: oracle invalid"); // Scale the oracle price by token decimals delta if necessary uint256 scalingFactor; if (decimalsNormalizer < 0) { scalingFactor = 10 ** (-1 * decimalsNormalizer).toUint256(); _peg = _peg.div(scalingFactor); } else { scalingFactor = 10 ** decimalsNormalizer.toUint256(); _peg = _peg.mul(scalingFactor); } // Invert the oracle price if necessary if (doInvert) { _peg = invert(_peg); } return _peg; } function _setOracle(address newOracle) internal { require(newOracle != address(0), "OracleRef: zero address"); address oldOracle = address(oracle); oracle = IOracle(newOracle); emit OracleUpdate(oldOracle, newOracle); } // Supports zero address if no backup function _setBackupOracle(address newBackupOracle) internal { address oldBackupOracle = address(backupOracle); backupOracle = IOracle(newBackupOracle); emit BackupOracleUpdate(oldBackupOracle, newBackupOracle); } function _setDoInvert(bool newDoInvert) internal { bool oldDoInvert = doInvert; doInvert = newDoInvert; if (oldDoInvert != newDoInvert) { _setDecimalsNormalizer( -1 * decimalsNormalizer); } emit InvertUpdate(oldDoInvert, newDoInvert); } function _setDecimalsNormalizer(int256 newDecimalsNormalizer) internal { int256 oldDecimalsNormalizer = decimalsNormalizer; decimalsNormalizer = newDecimalsNormalizer; emit DecimalsNormalizerUpdate(oldDecimalsNormalizer, newDecimalsNormalizer); } function _setDecimalsNormalizerFromToken(address token) internal { int256 feiDecimals = 18; int256 _decimalsNormalizer = feiDecimals - int256(uint256(IERC20Metadata(token).decimals())); if (doInvert) { _decimalsNormalizer = -1 * _decimalsNormalizer; } _setDecimalsNormalizer(_decimalsNormalizer); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../oracle/IOracle.sol"; /// @title OracleRef interface /// @author Fei Protocol interface IOracleRef { // ----------- Events ----------- event OracleUpdate(address indexed oldOracle, address indexed newOracle); event InvertUpdate(bool oldDoInvert, bool newDoInvert); event DecimalsNormalizerUpdate(int256 oldDecimalsNormalizer, int256 newDecimalsNormalizer); event BackupOracleUpdate(address indexed oldBackupOracle, address indexed newBackupOracle); // ----------- State changing API ----------- function updateOracle() external; // ----------- Governor only state changing API ----------- function setOracle(address newOracle) external; function setBackupOracle(address newBackupOracle) external; function setDecimalsNormalizer(int256 newDecimalsNormalizer) external; function setDoInvert(bool newDoInvert) external; // ----------- Getters ----------- function oracle() external view returns (IOracle); function backupOracle() external view returns (IOracle); function doInvert() external view returns (bool); function decimalsNormalizer() external view returns (int256); function readOracle() external view returns (Decimal.D256 memory); function invert(Decimal.D256 calldata price) external pure returns (Decimal.D256 memory); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../external/Decimal.sol"; /// @title generic oracle interface for Fei Protocol /// @author Fei Protocol interface IOracle { // ----------- Events ----------- event Update(uint256 _peg); // ----------- State changing API ----------- function update() external; // ----------- Getters ----------- function read() external view returns (Decimal.D256 memory, bool); function isOutdated() external view returns (bool); } /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Empty Set Squad <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.4; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 private constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({ value: 0 }); } function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function from( uint256 a ) internal pure returns (D256 memory) { return D256({ value: a.mul(BASE) }); } function ratio( uint256 a, uint256 b ) internal pure returns (D256 memory) { return D256({ value: getPartial(a, BASE, b) }); } // ============ Self Functions ============ function add( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE), reason) }); } function mul( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.mul(b) }); } function div( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.div(b) }); } function pow( D256 memory self, uint256 b ) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({ value: self.value }); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.value) }); } function sub( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value) }); } function sub( D256 memory self, D256 memory b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value, reason) }); } function mul( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, b.value, BASE) }); } function div( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, BASE, b.value) }); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo( D256 memory a, D256 memory b ) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@uniswap/v2-periphery/contracts/interfaces/IWETH.sol"; library Constants { /// @notice the denominator for basis points granularity (10,000) uint256 public constant BASIS_POINTS_GRANULARITY = 10_000; uint256 public constant ONE_YEAR = 365.25 days; /// @notice WETH9 address IWETH public constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); /// @notice USD stand-in address address public constant USD = 0x1111111111111111111111111111111111111111; /// @notice Wei per ETH, i.e. 10**18 uint256 public constant ETH_GRANULARITY = 1e18; /// @notice number of decimals in ETH, 18 uint256 public constant ETH_DECIMALS = 18; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 (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 (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); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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 SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; }
@notice withdraw ERC20 from the contract @param token address of the ERC20 to send @param to address destination of the ERC20 @param amount quantity of ERC20 to send
) public virtual override onlyPCVController { _withdrawERC20(token, to, amount); }
292,331
[ 1, 1918, 9446, 4232, 39, 3462, 628, 326, 6835, 225, 1147, 1758, 434, 326, 4232, 39, 3462, 358, 1366, 225, 358, 1758, 2929, 434, 326, 4232, 39, 3462, 225, 3844, 10457, 434, 4232, 39, 3462, 358, 1366, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 262, 1071, 5024, 3849, 1338, 3513, 58, 2933, 288, 203, 3639, 389, 1918, 9446, 654, 39, 3462, 12, 2316, 16, 358, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.7; library SafeMath { function ADD107(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING c = a + b; assert(c >= a); return c; } function SUB463(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING assert(b <= a); return a - b; } function MUL691(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function DIV78(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return a / b; } function MOD635(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } interface IERC20{ function NAME279() external view returns (string memory); //inject NONSTANDARD NAMING function SYMBOL160() external view returns (string memory); //inject NONSTANDARD NAMING function DECIMALS981() external view returns (uint256); //inject NONSTANDARD NAMING function TOTALSUPPLY34() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF441(address owner) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER28(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM551(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE505(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE331(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER884(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL336(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract Ownable { address internal _owner; event OWNERSHIPTRANSFERRED839(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = msg.sender; emit OWNERSHIPTRANSFERRED839(address(0), _owner); } function OWNER665() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER540() { //inject NONSTANDARD NAMING require(msg.sender == _owner); _; } function TRANSFEROWNERSHIP744(address newOwner) external ONLYOWNER540 { //inject NONSTANDARD NAMING require(newOwner != address(0)); _owner = newOwner; emit OWNERSHIPTRANSFERRED839(_owner, newOwner); } function RESCUETOKENS997(address tokenAddr, address receiver, uint256 amount) external ONLYOWNER540 { //inject NONSTANDARD NAMING IERC20 _token = IERC20(tokenAddr); require(receiver != address(0)); uint256 balance = _token.BALANCEOF441(address(this)); require(balance >= amount); assert(_token.TRANSFER28(receiver, amount)); } function WITHDRAWETHER684(address payable to, uint256 amount) external ONLYOWNER540 { //inject NONSTANDARD NAMING require(to != address(0)); uint256 balance = address(this).balance; require(balance >= amount); to.transfer(amount); } } contract Pausable is Ownable { bool private _paused; event PAUSED954(address account); //inject NONSTANDARD NAMING event UNPAUSED286(address account); //inject NONSTANDARD NAMING constructor () internal { _paused = false; } function PAUSED229() public view returns (bool) { //inject NONSTANDARD NAMING return _paused; } modifier WHENNOTPAUSED225() { //inject NONSTANDARD NAMING require(!_paused); _; } modifier WHENPAUSED333() { //inject NONSTANDARD NAMING require(_paused); _; } function PAUSE345() external ONLYOWNER540 WHENNOTPAUSED225 { //inject NONSTANDARD NAMING _paused = true; emit PAUSED954(msg.sender); } function UNPAUSE328() external ONLYOWNER540 WHENPAUSED333 { //inject NONSTANDARD NAMING _paused = false; emit UNPAUSED286(msg.sender); } } contract ChainOfFaith is Ownable, Pausable, IERC20 { using SafeMath for uint256; string private _name = "ChainOfFaith"; string private _symbol = "XKY"; uint256 private _decimals = 18; // 18 decimals uint256 private _cap = 2000000000 * 10 **_decimals; // 1 billion cap uint256 private _totalSupply; mapping (address => bool) private _minter; event MINT409(address indexed to, uint256 value); //inject NONSTANDARD NAMING event MINTERCHANGED454(address account, bool state); //inject NONSTANDARD NAMING mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; event DONATE221(address indexed account, uint256 amount); //inject NONSTANDARD NAMING constructor() public { _minter[msg.sender] = true; } function () external payable { emit DONATE221(msg.sender, msg.value); } function NAME279() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL160() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS981() public view returns (uint256) { //inject NONSTANDARD NAMING return _decimals; } function CAP336() public view returns (uint256) { //inject NONSTANDARD NAMING return _cap; } function TOTALSUPPLY34() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF441(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE331(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER28(address to, uint256 value) public WHENNOTPAUSED225 returns (bool) { //inject NONSTANDARD NAMING // Normal Transfer _TRANSFER463(msg.sender, to, value); return true; } function APPROVE505(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE461(msg.sender, spender, value); return true; } function INCREASEALLOWANCE237(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE461(msg.sender, spender, _allowed[msg.sender][spender].ADD107(addedValue)); return true; } function DECREASEALLOWANCE179(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE461(msg.sender, spender, _allowed[msg.sender][spender].SUB463(subtractedValue)); return true; } function TRANSFERFROM551(address from, address to, uint256 value) public WHENNOTPAUSED225 returns (bool) { //inject NONSTANDARD NAMING require(_allowed[from][msg.sender] >= value); _TRANSFER463(from, to, value); _APPROVE461(from, msg.sender, _allowed[from][msg.sender].SUB463(value)); return true; } function _TRANSFER463(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB463(value); _balances[to] = _balances[to].ADD107(value); emit TRANSFER884(from, to, value); } function _APPROVE461(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require(owner != address(0)); require(spender != address(0)); _allowed[owner][spender] = value; emit APPROVAL336(owner, spender, value); } modifier ONLYMINTER928() { //inject NONSTANDARD NAMING require(_minter[msg.sender]); _; } function ISMINTER255(address account) public view returns (bool) { //inject NONSTANDARD NAMING return _minter[account]; } function SETMINTERSTATE291(address account, bool state) external ONLYOWNER540 { //inject NONSTANDARD NAMING _minter[account] = state; emit MINTERCHANGED454(account, state); } function MINT898(address to, uint256 value) public ONLYMINTER928 returns (bool) { //inject NONSTANDARD NAMING _MINT906(to, value); return true; } function _MINT906(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(_totalSupply.ADD107(value) <= _cap); require(account != address(0)); _totalSupply = _totalSupply.ADD107(value); _balances[account] = _balances[account].ADD107(value); emit MINT409(account, value); emit TRANSFER884(address(0), account, value); } }
inject NONSTANDARD NAMING
function NAME279() public view returns (string memory) {
7,319,091
[ 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, 6048, 5324, 29, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xc8BF18f0d422A0Abdec1B3540492dA3aCb6603BA/sources/contracts/interfaces/ZoneInterface.sol
Called by Consideration whenever extraData is not provided by the caller. Called by Consideration whenever any extraData is provided by the caller.
interface ZoneInterface { event Paused(); event Unpaused(); function isValidOrder( bytes32 orderHash, address caller, address offerer, bytes32 zoneHash ) external view returns (bytes4 validOrderMagicValue); function isValidOrderIncludingExtraData( bytes32 orderHash, address caller, AdvancedOrder calldata order, bytes32[] calldata priorOrderHashes, CriteriaResolver[] calldata criteriaResolvers ) external view returns (bytes4 validOrderMagicValue); }
9,253,770
[ 1, 8185, 635, 23047, 367, 17334, 2870, 751, 353, 486, 2112, 635, 326, 4894, 18, 11782, 635, 23047, 367, 17334, 1281, 2870, 751, 353, 2112, 635, 326, 4894, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 10912, 1358, 288, 203, 565, 871, 21800, 3668, 5621, 203, 203, 565, 871, 1351, 8774, 3668, 5621, 203, 203, 565, 445, 4908, 2448, 12, 203, 3639, 1731, 1578, 1353, 2310, 16, 203, 3639, 1758, 4894, 16, 203, 3639, 1758, 10067, 264, 16, 203, 3639, 1731, 1578, 4157, 2310, 203, 565, 262, 3903, 1476, 1135, 261, 3890, 24, 923, 2448, 19289, 620, 1769, 203, 203, 565, 445, 4908, 2448, 382, 18596, 7800, 751, 12, 203, 3639, 1731, 1578, 1353, 2310, 16, 203, 3639, 1758, 4894, 16, 203, 3639, 27451, 2448, 745, 892, 1353, 16, 203, 3639, 1731, 1578, 8526, 745, 892, 6432, 2448, 14455, 16, 203, 3639, 8356, 4301, 8526, 745, 892, 3582, 28715, 203, 565, 262, 3903, 1476, 1135, 261, 3890, 24, 923, 2448, 19289, 620, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-09-28 */ // SPDX-License-Identifier: MIT pragma solidity 0.6.8; // /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // /** * @dev 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) { // 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); } } } } // /** * @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"); } } } // /** * @notice Interface for Curve.fi's REN pool. * Note that we are using array of 2 as Curve's REN pool contains only WBTC and renBTC. */ interface ICurveFi { function get_virtual_price() external view returns (uint256); function add_liquidity( // renBTC pool uint256[2] calldata amounts, uint256 min_mint_amount ) external; function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[2] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; } // /** * @notice Interface for Curve.fi's liquidity guage. */ interface ICurveGauge { function deposit(uint256) external; function balanceOf(address) external view returns (uint256); function withdraw(uint256) external; } // /** * @notice Interface for Curve.fi's CRV minter. */ interface ICurveMinter { function mint(address) external; } // /** * @notice Interface for Uniswap's router. */ interface IUniswapRouter { function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external; } // /** * @notice Interface for Strategies. */ interface IStrategy { /** * @dev Returns the token address that the strategy expects. */ function want() external view returns (address); /** * @dev Returns the total amount of tokens deposited in this strategy. */ function balanceOf() external view returns (uint256); /** * @dev Deposits the token to start earning. */ function deposit() external; /** * @dev Withdraws partial funds from the strategy. */ function withdraw(uint256 _amount) external; /** * @dev Withdraws all funds from the strategy. */ function withdrawAll() external returns (uint256); /** * @dev Claims yield and convert it back to want token. */ function harvest() external; } // /** * @dev Earning strategy that accepts renCRV, earns CRV and converts CRV back to renCRV as yield. */ contract StrategyCurveRenBTC is IStrategy { using SafeERC20 for IERC20; using SafeMath for uint256; event Harvested(address indexed token, uint256 amount); address internal constant override want = address(0x49849C98ae39Fff122806C06791Fa73784FB3675); // renCrv token address internal constant pool = address(0xB1F2cdeC61db658F091671F5f199635aEF202CAC); // renCrv guage address internal constant mintr = address(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0); // Token minter address internal constant crv = address(0xD533a949740bb3306d119CC777fa900bA034cd52); // CRV token address internal constant uni = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2Router02 address internal constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // WETH token. Used for crv <> weth <> wbtc route address internal constant wbtc = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); // WBTC token address internal constant curve = address(0x93054188d876f558f4a66B2EF1d97d16eDf0895B); // REN swap address internal vault; constructor(address _vault) public { require(_vault != address(0x0), "vault not set"); vault = _vault; } /** * @dev Deposits all renCRV into Curve liquidity gauge to earn CRV. */ function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if (_want > 0) { IERC20(want).safeApprove(pool, 0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC IERC20(want).safeApprove(pool, _want); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC ICurveGauge(pool).deposit(_want); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } } /** * @dev Withdraw partial funds, normally used with a vault withdrawal */ function withdraw(uint256 _amount) public override { require(msg.sender == vault, "not vault"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC uint256 _balance = IERC20(want).balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } IERC20(want).safeTransfer(vault, _amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @dev Withdraw all funds, normally used when migrating strategies */ function withdrawAll() public override returns (uint256 balance) { require(msg.sender == vault, "not vault"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC ICurveGauge(pool).withdraw(ICurveGauge(pool).balanceOf(address(this))); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC balance = IERC20(want).balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC IERC20(want).safeTransfer(vault, balance); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @dev Claims CRV from Curve and convert it back to renCRV. * Anyone can trigger the harvest! */ function harvest() public override { // Claims CRV from Curve ICurveMinter(mintr).mint(pool); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC uint256 _crv = IERC20(crv).balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC // Uniswap: CRV --> WETH --> WBTC if (_crv > 0) { IERC20(crv).safeApprove(uni, 0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC IERC20(crv).safeApprove(uni, _crv); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC address[] memory path = new address[](3); path[0] = crv; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC path[1] = weth; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC path[2] = wbtc; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC IUniswapRouter(uni).swapExactTokensForTokens(_crv, uint256(0), path, address(this), now.add(1800)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } // Curve: WBTC --> renCRV uint256 _wbtc = IERC20(wbtc).balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if (_wbtc > 0) { IERC20(wbtc).safeApprove(curve, 0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC IERC20(wbtc).safeApprove(curve, _wbtc); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC ICurveFi(curve).add_liquidity([0, _wbtc], 0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } uint256 _want = IERC20(want).balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if (_want > 0) { deposit(); } emit Harvested(want, _want); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @dev Withdraw some tokens from the gauge. */ function _withdrawSome(uint256 _amount) internal returns (uint256) { ICurveGauge(pool).withdraw(_amount); return _amount; } /** * @dev Returns the amount of tokens deposited in the strategy. */ function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @dev Returns the amount of tokens deposited in the gauge. */ function balanceOfPool() public view returns (uint256) { return ICurveGauge(pool).balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @dev Returns the amount of tokens deposited in strategy + gauge. */ function balanceOf() public view override returns (uint256) { return balanceOfWant().add(balanceOfPool()); } }
inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
ICurveFi(curve).add_liquidity([0, _wbtc], 0);
12,905,136
[ 1, 22170, 18708, 14939, 8350, 13255, 40, 6953, 17187, 478, 21163, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 467, 9423, 42, 77, 12, 16683, 2934, 1289, 67, 549, 372, 24237, 3816, 20, 16, 389, 9464, 5111, 6487, 374, 1769, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xa101d2cd94572B9c4f9F842DfD6336Bef77b9E62/sources/src/commons/receiver/Receiver.sol
return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))
function onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) { return 0x150b7a02; }
2,905,783
[ 1, 2463, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 265, 654, 39, 27, 5340, 8872, 12, 2867, 16, 2867, 16, 11890, 5034, 16, 3890, 2225, 3719, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 603, 654, 39, 27, 5340, 8872, 12, 2867, 16, 1758, 16, 2254, 5034, 16, 1731, 745, 892, 13, 3903, 16618, 1135, 261, 3890, 24, 13, 288, 203, 565, 327, 374, 92, 23014, 70, 27, 69, 3103, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.17; pragma experimental ABIEncoderV2; interface iuniswap2 { //inject NONSTANDARD NAMING // To convert DAI to ETH function SWAPEXACTTOKENSFORETH53(uint AMOUNTIN88, uint AMOUNTOUTMIN99, address[] calldata PATH78, address TO76, uint DEADLINE33) external returns (uint[] memory AMOUNTS56); //inject NONSTANDARD NAMING // To convert ETH to YELD and burn it function SWAPEXACTETHFORTOKENS6(uint AMOUNTOUTMIN99, address[] calldata PATH78, address TO76, uint DEADLINE33) external payable returns (uint[] memory AMOUNTS56); //inject NONSTANDARD NAMING } interface ierc2093 { //inject NONSTANDARD NAMING function TOTALSUPPLY70() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF25(address ACCOUNT45) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER37(address RECIPIENT39, uint256 AMOUNT4) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE65(address OWNER26, address SPENDER52) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE3(address SPENDER52, uint256 AMOUNT4) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM19(address SENDER75, address RECIPIENT39, uint256 AMOUNT4) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER22(address indexed FROM88, address indexed TO76, uint256 VALUE83); //inject NONSTANDARD NAMING event APPROVAL93(address indexed OWNER26, address indexed SPENDER52, uint256 VALUE83); //inject NONSTANDARD NAMING } contract context61 { //inject NONSTANDARD NAMING constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER82() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA79() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract ownable93 is context61 { //inject NONSTANDARD NAMING address payable private _OWNER43; //inject NONSTANDARD NAMING event OWNERSHIPTRANSFERRED63(address indexed PREVIOUSOWNER24, address indexed NEWOWNER52); //inject NONSTANDARD NAMING constructor () internal { _OWNER43 = _MSGSENDER82(); emit OWNERSHIPTRANSFERRED63(address(0), _OWNER43); } function OWNER99() public view returns (address payable) { //inject NONSTANDARD NAMING return _OWNER43; } modifier ONLYOWNER61() { //inject NONSTANDARD NAMING require(ISOWNER2(), "Ownable: caller is not the owner"); _; } function ISOWNER2() public view returns (bool) { //inject NONSTANDARD NAMING return _MSGSENDER82() == _OWNER43; } function RENOUNCEOWNERSHIP13() public ONLYOWNER61 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED63(_OWNER43, address(0)); _OWNER43 = address(0); } function TRANSFEROWNERSHIP7(address payable NEWOWNER52) public ONLYOWNER61 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP60(NEWOWNER52); } function _TRANSFEROWNERSHIP60(address payable NEWOWNER52) internal { //inject NONSTANDARD NAMING require(NEWOWNER52 != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED63(_OWNER43, NEWOWNER52); _OWNER43 = NEWOWNER52; } } contract erc2030 is context61, ierc2093 { //inject NONSTANDARD NAMING using safemath13 for uint256; mapping (address => uint256) _BALANCES15; //inject NONSTANDARD NAMING mapping (address => mapping (address => uint256)) private _ALLOWANCES69; //inject NONSTANDARD NAMING uint256 _TOTALSUPPLY32; //inject NONSTANDARD NAMING function TOTALSUPPLY70() public view returns (uint256) { //inject NONSTANDARD NAMING return _TOTALSUPPLY32; } function BALANCEOF25(address ACCOUNT45) public view returns (uint256) { //inject NONSTANDARD NAMING return _BALANCES15[ACCOUNT45]; } function TRANSFER37(address RECIPIENT39, uint256 AMOUNT4) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER95(_MSGSENDER82(), RECIPIENT39, AMOUNT4); return true; } function ALLOWANCE65(address OWNER26, address SPENDER52) public view returns (uint256) { //inject NONSTANDARD NAMING return _ALLOWANCES69[OWNER26][SPENDER52]; } function APPROVE3(address SPENDER52, uint256 AMOUNT4) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE30(_MSGSENDER82(), SPENDER52, AMOUNT4); return true; } function TRANSFERFROM19(address SENDER75, address RECIPIENT39, uint256 AMOUNT4) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER95(SENDER75, RECIPIENT39, AMOUNT4); _APPROVE30(SENDER75, _MSGSENDER82(), _ALLOWANCES69[SENDER75][_MSGSENDER82()].SUB57(AMOUNT4, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE47(address SPENDER52, uint256 ADDEDVALUE76) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE30(_MSGSENDER82(), SPENDER52, _ALLOWANCES69[_MSGSENDER82()][SPENDER52].ADD27(ADDEDVALUE76)); return true; } function DECREASEALLOWANCE20(address SPENDER52, uint256 SUBTRACTEDVALUE75) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE30(_MSGSENDER82(), SPENDER52, _ALLOWANCES69[_MSGSENDER82()][SPENDER52].SUB57(SUBTRACTEDVALUE75, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER95(address SENDER75, address RECIPIENT39, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(SENDER75 != address(0), "ERC20: transfer from the zero address"); require(RECIPIENT39 != address(0), "ERC20: transfer to the zero address"); _BALANCES15[SENDER75] = _BALANCES15[SENDER75].SUB57(AMOUNT4, "ERC20: transfer amount exceeds balance"); _BALANCES15[RECIPIENT39] = _BALANCES15[RECIPIENT39].ADD27(AMOUNT4); emit TRANSFER22(SENDER75, RECIPIENT39, AMOUNT4); } function _MINT79(address ACCOUNT45, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(ACCOUNT45 != address(0), "ERC20: mint to the zero address"); _TOTALSUPPLY32 = _TOTALSUPPLY32.ADD27(AMOUNT4); _BALANCES15[ACCOUNT45] = _BALANCES15[ACCOUNT45].ADD27(AMOUNT4); emit TRANSFER22(address(0), ACCOUNT45, AMOUNT4); } function _BURN68(address ACCOUNT45, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(ACCOUNT45 != address(0), "ERC20: burn from the zero address"); _BALANCES15[ACCOUNT45] = _BALANCES15[ACCOUNT45].SUB57(AMOUNT4, "ERC20: burn amount exceeds balance"); _TOTALSUPPLY32 = _TOTALSUPPLY32.SUB57(AMOUNT4); emit TRANSFER22(ACCOUNT45, address(0), AMOUNT4); } function _APPROVE30(address OWNER26, address SPENDER52, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(OWNER26 != address(0), "ERC20: approve from the zero address"); require(SPENDER52 != address(0), "ERC20: approve to the zero address"); _ALLOWANCES69[OWNER26][SPENDER52] = AMOUNT4; emit APPROVAL93(OWNER26, SPENDER52, AMOUNT4); } function _BURNFROM66(address ACCOUNT45, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING _BURN68(ACCOUNT45, AMOUNT4); _APPROVE30(ACCOUNT45, _MSGSENDER82(), _ALLOWANCES69[ACCOUNT45][_MSGSENDER82()].SUB57(AMOUNT4, "ERC20: burn amount exceeds allowance")); } } contract erc20detailed21 is ierc2093 { //inject NONSTANDARD NAMING string private _NAME42; //inject NONSTANDARD NAMING string private _SYMBOL85; //inject NONSTANDARD NAMING uint8 private _DECIMALS78; //inject NONSTANDARD NAMING constructor (string memory NAME99, string memory SYMBOL38, uint8 DECIMALS96) public { //inject NONSTANDARD NAMING _NAME42 = NAME99; _SYMBOL85 = SYMBOL38; _DECIMALS78 = DECIMALS96; } function NAME45() public view returns (string memory) { //inject NONSTANDARD NAMING return _NAME42; } function SYMBOL75() public view returns (string memory) { //inject NONSTANDARD NAMING return _SYMBOL85; } function DECIMALS63() public view returns (uint8) { //inject NONSTANDARD NAMING return _DECIMALS78; } } contract reentrancyguard94 { //inject NONSTANDARD NAMING uint256 private _GUARDCOUNTER38; //inject NONSTANDARD NAMING constructor () internal { _GUARDCOUNTER38 = 1; } modifier NONREENTRANT47() { //inject NONSTANDARD NAMING _GUARDCOUNTER38 += 1; uint256 LOCALCOUNTER54 = _GUARDCOUNTER38; //inject NONSTANDARD NAMING _; require(LOCALCOUNTER54 == _GUARDCOUNTER38, "ReentrancyGuard: reentrant call"); } } library safemath13 { //inject NONSTANDARD NAMING function ADD27(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 C51 = A32 + B30; //inject NONSTANDARD NAMING require(C51 >= A32, "SafeMath: addition overflow"); return C51; } function SUB57(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB57(A32, B30, "SafeMath: subtraction overflow"); } function SUB57(uint256 A32, uint256 B30, string memory ERRORMESSAGE15) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(B30 <= A32, ERRORMESSAGE15); uint256 C51 = A32 - B30; //inject NONSTANDARD NAMING return C51; } function MUL24(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (A32 == 0) { return 0; } uint256 C51 = A32 * B30; //inject NONSTANDARD NAMING require(C51 / A32 == B30, "SafeMath: multiplication overflow"); return C51; } function DIV26(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV26(A32, B30, "SafeMath: division by zero"); } function DIV26(uint256 A32, uint256 B30, string memory ERRORMESSAGE15) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(B30 > 0, ERRORMESSAGE15); uint256 C51 = A32 / B30; //inject NONSTANDARD NAMING return C51; } function MOD76(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD76(A32, B30, "SafeMath: modulo by zero"); } function MOD76(uint256 A32, uint256 B30, string memory ERRORMESSAGE15) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(B30 != 0, ERRORMESSAGE15); return A32 % B30; } } library address92 { //inject NONSTANDARD NAMING function ISCONTRACT77(address ACCOUNT45) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 CODEHASH48; //inject NONSTANDARD NAMING bytes32 ACCOUNTHASH81 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; //inject NONSTANDARD NAMING // solhint-disable-next-line no-inline-assembly assembly { CODEHASH48 := extcodehash(ACCOUNT45) } return (CODEHASH48 != 0x0 && CODEHASH48 != ACCOUNTHASH81); } function TOPAYABLE47(address ACCOUNT45) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(ACCOUNT45)); } function SENDVALUE65(address payable RECIPIENT39, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(address(this).balance >= AMOUNT4, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool SUCCESS17, ) = RECIPIENT39.call.value(AMOUNT4)(""); //inject NONSTANDARD NAMING require(SUCCESS17, "Address: unable to send value, recipient may have reverted"); } } library safeerc2059 { //inject NONSTANDARD NAMING using safemath13 for uint256; using address92 for address; function SAFETRANSFER30(ierc2093 TOKEN25, address TO76, uint256 VALUE83) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.TRANSFER37.selector, TO76, VALUE83)); } function SAFETRANSFERFROM76(ierc2093 TOKEN25, address FROM88, address TO76, uint256 VALUE83) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.TRANSFERFROM19.selector, FROM88, TO76, VALUE83)); } function SAFEAPPROVE32(ierc2093 TOKEN25, address SPENDER52, uint256 VALUE83) internal { //inject NONSTANDARD NAMING require((VALUE83 == 0) || (TOKEN25.ALLOWANCE65(address(this), SPENDER52) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.APPROVE3.selector, SPENDER52, VALUE83)); } function SAFEINCREASEALLOWANCE32(ierc2093 TOKEN25, address SPENDER52, uint256 VALUE83) internal { //inject NONSTANDARD NAMING uint256 NEWALLOWANCE45 = TOKEN25.ALLOWANCE65(address(this), SPENDER52).ADD27(VALUE83); //inject NONSTANDARD NAMING CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.APPROVE3.selector, SPENDER52, NEWALLOWANCE45)); } function SAFEDECREASEALLOWANCE48(ierc2093 TOKEN25, address SPENDER52, uint256 VALUE83) internal { //inject NONSTANDARD NAMING uint256 NEWALLOWANCE45 = TOKEN25.ALLOWANCE65(address(this), SPENDER52).SUB57(VALUE83, "SafeERC20: decreased allowance below zero"); //inject NONSTANDARD NAMING CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.APPROVE3.selector, SPENDER52, NEWALLOWANCE45)); } function CALLOPTIONALRETURN90(ierc2093 TOKEN25, bytes memory DATA85) private { //inject NONSTANDARD NAMING require(address(TOKEN25).ISCONTRACT77(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool SUCCESS17, bytes memory RETURNDATA42) = address(TOKEN25).call(DATA85); //inject NONSTANDARD NAMING require(SUCCESS17, "SafeERC20: low-level call failed"); if (RETURNDATA42.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(RETURNDATA42, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface compound17 { //inject NONSTANDARD NAMING function MINT37 ( uint256 MINTAMOUNT46 ) external returns ( uint256 ); //inject NONSTANDARD NAMING function REDEEM71(uint256 REDEEMTOKENS65) external returns (uint256); //inject NONSTANDARD NAMING function EXCHANGERATESTORED22() external view returns (uint); //inject NONSTANDARD NAMING } interface fulcrum27 { //inject NONSTANDARD NAMING function MINT37(address RECEIVER66, uint256 AMOUNT4) external payable returns (uint256 MINTAMOUNT46); //inject NONSTANDARD NAMING function BURN1(address RECEIVER66, uint256 BURNAMOUNT5) external returns (uint256 LOANAMOUNTPAID4); //inject NONSTANDARD NAMING function ASSETBALANCEOF38(address _OWNER43) external view returns (uint256 BALANCE2); //inject NONSTANDARD NAMING } interface ilendingpooladdressesprovider93 { //inject NONSTANDARD NAMING function GETLENDINGPOOL88() external view returns (address); //inject NONSTANDARD NAMING } interface aave60 { //inject NONSTANDARD NAMING function DEPOSIT43(address _RESERVE54, uint256 _AMOUNT50, uint16 _REFERRALCODE69) external; //inject NONSTANDARD NAMING } interface atoken49 { //inject NONSTANDARD NAMING function REDEEM71(uint256 AMOUNT4) external; //inject NONSTANDARD NAMING } interface iiearnmanager83 { //inject NONSTANDARD NAMING function RECOMMEND99(address _TOKEN3) external view returns ( //inject NONSTANDARD NAMING string memory CHOICE41, //inject NONSTANDARD NAMING uint256 CAPR5, //inject NONSTANDARD NAMING uint256 IAPR100, //inject NONSTANDARD NAMING uint256 AAPR96, //inject NONSTANDARD NAMING uint256 DAPR97 //inject NONSTANDARD NAMING ); } contract structs50 { //inject NONSTANDARD NAMING struct Val { uint256 VALUE83; //inject NONSTANDARD NAMING } enum ActionType { Deposit, // supply tokens Withdraw // borrow tokens } enum AssetDenomination { Wei // the amount is denominated in wei } enum AssetReference { Delta // the amount is given as a delta from the current value } struct AssetAmount { bool SIGN32; // true if positive //inject NONSTANDARD NAMING AssetDenomination DENOMINATION0; //inject NONSTANDARD NAMING AssetReference REF97; //inject NONSTANDARD NAMING uint256 VALUE83; //inject NONSTANDARD NAMING } struct ActionArgs { ActionType ACTIONTYPE60; //inject NONSTANDARD NAMING uint256 ACCOUNTID6; //inject NONSTANDARD NAMING AssetAmount AMOUNT4; //inject NONSTANDARD NAMING uint256 PRIMARYMARKETID93; //inject NONSTANDARD NAMING uint256 SECONDARYMARKETID1; //inject NONSTANDARD NAMING address OTHERADDRESS81; //inject NONSTANDARD NAMING uint256 OTHERACCOUNTID93; //inject NONSTANDARD NAMING bytes DATA85; //inject NONSTANDARD NAMING } struct Info { address OWNER26; // The address that owns the account //inject NONSTANDARD NAMING uint256 NUMBER25; // A nonce that allows a single address to control many accounts //inject NONSTANDARD NAMING } struct Wei { bool SIGN32; // true if positive //inject NONSTANDARD NAMING uint256 VALUE83; //inject NONSTANDARD NAMING } } contract dydx100 is structs50 { //inject NONSTANDARD NAMING function GETACCOUNTWEI65(Info memory ACCOUNT45, uint256 MARKETID4) public view returns (Wei memory); //inject NONSTANDARD NAMING function OPERATE53(Info[] memory, ActionArgs[] memory) public; //inject NONSTANDARD NAMING } interface lendingpooladdressesprovider85 { //inject NONSTANDARD NAMING function GETLENDINGPOOL88() external view returns (address); //inject NONSTANDARD NAMING function GETLENDINGPOOLCORE37() external view returns (address); //inject NONSTANDARD NAMING } contract yusdc19 is erc2030, erc20detailed21, reentrancyguard94, structs50, ownable93 { //inject NONSTANDARD NAMING using safeerc2059 for ierc2093; using address92 for address; using safemath13 for uint256; struct Deposit { uint256 AMOUNT4; //inject NONSTANDARD NAMING uint256 START33; // Block when it started //inject NONSTANDARD NAMING } uint256 public POOL37; //inject NONSTANDARD NAMING address public TOKEN25; //inject NONSTANDARD NAMING address public COMPOUND53; //inject NONSTANDARD NAMING address public FULCRUM19; //inject NONSTANDARD NAMING address public AAVE10; //inject NONSTANDARD NAMING address public AAVEPOOL17; //inject NONSTANDARD NAMING address public AAVETOKEN8; //inject NONSTANDARD NAMING address public DYDX62; //inject NONSTANDARD NAMING uint256 public DTOKEN6; //inject NONSTANDARD NAMING address public APR50; //inject NONSTANDARD NAMING address public CHAI29; //inject NONSTANDARD NAMING // Add other tokens if implemented for another stablecoin address public UNISWAPROUTER94 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //inject NONSTANDARD NAMING address public USDC51 = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; //inject NONSTANDARD NAMING address public WETH0 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //inject NONSTANDARD NAMING address payable public RETIREMENTYELDTREASURY39; //inject NONSTANDARD NAMING ierc2093 public YELDTOKEN43; //inject NONSTANDARD NAMING uint256 public MAXIMUMTOKENSTOBURN49 = 50000 * 1e18; //inject NONSTANDARD NAMING uint256 public constant minimumeffectamount5 = 5 * 10 ** 18; //inject NONSTANDARD NAMING // When you stake say 1000 USDC for a day that will be your maximum // if you stake the next time 300 USDC your maximum will stay the same // if you stake 2000 at once it will increase to 2000 USDC mapping(bytes32 => uint256) public NUMBEROFPARTICIPANTS77; //inject NONSTANDARD NAMING mapping(address => Deposit) public DEPOSITS12; //inject NONSTANDARD NAMING uint256 public constant onedayinblocks19 = 6500; //inject NONSTANDARD NAMING uint256 public YELDTOREWARDPERDAY12 = 100e18; // 100 YELD per day per 1 million stablecoins padded with 18 zeroes to have that flexibility //inject NONSTANDARD NAMING uint256 public constant onemillion14 = 1e6; //inject NONSTANDARD NAMING enum Lender { NONE, DYDX, COMPOUND, AAVE, FULCRUM } Lender public PROVIDER42 = Lender.NONE; //inject NONSTANDARD NAMING constructor (address _YELDTOKEN72, address payable _RETIREMENTYELDTREASURY14) public payable erc20detailed21("yearn USDC", "yUSDC", 18) { //inject NONSTANDARD NAMING TOKEN25 = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); APR50 = address(0xdD6d648C991f7d47454354f4Ef326b04025a48A8); DYDX62 = address(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e); AAVE10 = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); AAVEPOOL17 = address(0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3); FULCRUM19 = address(0x493C57C4763932315A328269E1ADaD09653B9081); AAVETOKEN8 = address(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d); COMPOUND53 = address(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); CHAI29 = address(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215); DTOKEN6 = 3; YELDTOKEN43 = ierc2093(_YELDTOKEN72); RETIREMENTYELDTREASURY39 = _RETIREMENTYELDTREASURY14; APPROVETOKEN12(); } // To receive ETH after converting it from USDC function () external payable {} function SETRETIREMENTYELDTREASURY49(address payable _TREASURY6) public ONLYOWNER61 { //inject NONSTANDARD NAMING RETIREMENTYELDTREASURY39 = _TREASURY6; } // In case a new uniswap router version is released function SETUNISWAPROUTER20(address _UNISWAPROUTER42) public ONLYOWNER61 { //inject NONSTANDARD NAMING UNISWAPROUTER94 = _UNISWAPROUTER42; } function EXTRACTTOKENSIFSTUCK53(address _TOKEN3, uint256 _AMOUNT50) public ONLYOWNER61 { //inject NONSTANDARD NAMING ierc2093(_TOKEN3).TRANSFER37(msg.sender, _AMOUNT50); } function EXTRACTETHIFSTUCK0() public ONLYOWNER61 { //inject NONSTANDARD NAMING OWNER99().transfer(address(this).balance); } function CHANGEYELDTOREWARDPERDAY13(uint256 _AMOUNT50) public ONLYOWNER61 { //inject NONSTANDARD NAMING YELDTOREWARDPERDAY12 = _AMOUNT50; } function GETGENERATEDYELDS73() public view returns(uint256) { //inject NONSTANDARD NAMING uint256 BLOCKSPASSED1; //inject NONSTANDARD NAMING if (DEPOSITS12[msg.sender].START33 > 0) { BLOCKSPASSED1 = block.number.SUB57(DEPOSITS12[msg.sender].START33); } else { BLOCKSPASSED1 = 0; } // This will work because amount is a token with 18 decimals // Take the deposit, reduce it by 1 million (by removing 6 zeroes) so you get 1 // That 1 means get 1 YELD per day (in blocks). Now multiply that 1 by 100 to get 100 YELD per day // your deposits in dai div by 1 million * by yeld to reward / 1e18 since yeldToReward is in 18 decimals to be able to provide a smaller price since // we can't go below 1 in a variable. You can't make the price 0.00001 that's why we need that 1e18 padding uint256 GENERATEDYELDS87 = DEPOSITS12[msg.sender].AMOUNT4.DIV26(onemillion14).MUL24(YELDTOREWARDPERDAY12.DIV26(1e18)).MUL24(BLOCKSPASSED1).DIV26(onedayinblocks19); //inject NONSTANDARD NAMING return GENERATEDYELDS87; } function EXTRACTYELDEARNINGSWHILEKEEPINGDEPOSIT99() public { //inject NONSTANDARD NAMING require(DEPOSITS12[msg.sender].START33 > 0 && DEPOSITS12[msg.sender].AMOUNT4 > 0, 'Must have deposited stablecoins beforehand'); uint256 GENERATEDYELDS87 = GETGENERATEDYELDS73(); //inject NONSTANDARD NAMING DEPOSITS12[msg.sender] = Deposit(DEPOSITS12[msg.sender].AMOUNT4, block.number); YELDTOKEN43.TRANSFER37(msg.sender, GENERATEDYELDS87); } function DEPOSIT43(uint256 _AMOUNT50) //inject NONSTANDARD NAMING external NONREENTRANT47 { require(_AMOUNT50 > 0, "deposit must be greater than 0"); POOL37 = CALCPOOLVALUEINTOKEN17(); ierc2093(TOKEN25).SAFETRANSFERFROM76(msg.sender, address(this), _AMOUNT50); // Yeld if (GETGENERATEDYELDS73() > 0) EXTRACTYELDEARNINGSWHILEKEEPINGDEPOSIT99(); DEPOSITS12[msg.sender] = Deposit(DEPOSITS12[msg.sender].AMOUNT4.ADD27(_AMOUNT50), block.number); // Yeld // Calculate pool shares uint256 SHARES22 = 0; //inject NONSTANDARD NAMING if (POOL37 == 0) { SHARES22 = _AMOUNT50; POOL37 = _AMOUNT50; } else { SHARES22 = (_AMOUNT50.MUL24(_TOTALSUPPLY32)).DIV26(POOL37); } POOL37 = CALCPOOLVALUEINTOKEN17(); _MINT79(msg.sender, SHARES22); } // Converts USDC to ETH and returns how much ETH has been received from Uniswap function USDCTOETH25(uint256 _AMOUNT50) internal returns(uint256) { //inject NONSTANDARD NAMING ierc2093(USDC51).SAFEAPPROVE32(UNISWAPROUTER94, 0); ierc2093(USDC51).SAFEAPPROVE32(UNISWAPROUTER94, _AMOUNT50); address[] memory PATH78 = new address[](2); //inject NONSTANDARD NAMING PATH78[0] = USDC51; PATH78[1] = WETH0; // swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) // 'amounts' is an array where [0] is input USDC amount and [1] is the resulting ETH after the conversion // even tho we've specified the WETH address, we'll receive ETH since that's how it works on uniswap // https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensforeth uint[] memory AMOUNTS56 = iuniswap2(UNISWAPROUTER94).SWAPEXACTTOKENSFORETH53(_AMOUNT50, uint(0), PATH78, address(this), now.ADD27(1800)); //inject NONSTANDARD NAMING return AMOUNTS56[1]; } // Buys YELD tokens paying in ETH on Uniswap and removes them from circulation // Returns how many YELD tokens have been burned function BUYNBURN98(uint256 _ETHTOSWAP66) internal returns(uint256) { //inject NONSTANDARD NAMING address[] memory PATH78 = new address[](2); //inject NONSTANDARD NAMING PATH78[0] = WETH0; PATH78[1] = address(YELDTOKEN43); // Burns the tokens by taking them out of circulation, sending them to the 0x0 address uint[] memory AMOUNTS56 = iuniswap2(UNISWAPROUTER94).SWAPEXACTETHFORTOKENS6.value(_ETHTOSWAP66)(uint(0), PATH78, address(0), now.ADD27(1800)); //inject NONSTANDARD NAMING return AMOUNTS56[1]; } // No rebalance implementation for lower fees and faster swaps function WITHDRAW27(uint256 _SHARES43) //inject NONSTANDARD NAMING external NONREENTRANT47 { require(_SHARES43 > 0, "withdraw must be greater than 0"); uint256 IBALANCE43 = BALANCEOF25(msg.sender); //inject NONSTANDARD NAMING require(_SHARES43 <= IBALANCE43, "insufficient balance"); POOL37 = CALCPOOLVALUEINTOKEN17(); uint256 R82 = (POOL37.MUL24(_SHARES43)).DIV26(_TOTALSUPPLY32); //inject NONSTANDARD NAMING _BALANCES15[msg.sender] = _BALANCES15[msg.sender].SUB57(_SHARES43, "redeem amount exceeds balance"); _TOTALSUPPLY32 = _TOTALSUPPLY32.SUB57(_SHARES43); emit TRANSFER22(msg.sender, address(0), _SHARES43); uint256 B30 = ierc2093(TOKEN25).BALANCEOF25(address(this)); //inject NONSTANDARD NAMING if (B30 < R82) { _WITHDRAWSOME38(R82.SUB57(B30)); } // Yeld uint256 GENERATEDYELDS87 = GETGENERATEDYELDS73(); //inject NONSTANDARD NAMING uint256 HALFPROFITS96 = (R82.SUB57(DEPOSITS12[msg.sender].AMOUNT4, '#3 Half profits sub error')).DIV26(2); //inject NONSTANDARD NAMING DEPOSITS12[msg.sender] = Deposit(DEPOSITS12[msg.sender].AMOUNT4.SUB57(_SHARES43), block.number); YELDTOKEN43.TRANSFER37(msg.sender, GENERATEDYELDS87); // Take a portion of the profits for the buy and burn and retirement yeld // Convert half the USDC earned into ETH for the protocol algorithms if (HALFPROFITS96 > minimumeffectamount5) { uint256 STAKINGPROFITS48 = USDCTOETH25(HALFPROFITS96); //inject NONSTANDARD NAMING uint256 TOKENSALREADYBURNED29 = YELDTOKEN43.BALANCEOF25(address(0)); //inject NONSTANDARD NAMING if (TOKENSALREADYBURNED29 < MAXIMUMTOKENSTOBURN49) { // 98% is the 49% doubled since we already took the 50% uint256 ETHTOSWAP53 = STAKINGPROFITS48.MUL24(98).DIV26(100); //inject NONSTANDARD NAMING // Buy and burn only applies up to 50k tokens burned BUYNBURN98(ETHTOSWAP53); // 1% for the Retirement Yield uint256 RETIREMENTYELD83 = STAKINGPROFITS48.MUL24(2).DIV26(100); //inject NONSTANDARD NAMING // Send to the treasury RETIREMENTYELDTREASURY39.transfer(RETIREMENTYELD83); } else { // If we've reached the maximum burn point, send half the profits to the treasury to reward holders uint256 RETIREMENTYELD83 = STAKINGPROFITS48; //inject NONSTANDARD NAMING // Send to the treasury RETIREMENTYELDTREASURY39.transfer(RETIREMENTYELD83); } } // Yeld ierc2093(TOKEN25).SAFETRANSFER30(msg.sender, R82); POOL37 = CALCPOOLVALUEINTOKEN17(); } function RECOMMEND99() public view returns (Lender) { //inject NONSTANDARD NAMING (,uint256 CAPR5,uint256 IAPR100,uint256 AAPR96,uint256 DAPR97) = iiearnmanager83(APR50).RECOMMEND99(TOKEN25); //inject NONSTANDARD NAMING uint256 MAX28 = 0; //inject NONSTANDARD NAMING if (CAPR5 > MAX28) { MAX28 = CAPR5; } if (IAPR100 > MAX28) { MAX28 = IAPR100; } if (AAPR96 > MAX28) { MAX28 = AAPR96; } if (DAPR97 > MAX28) { MAX28 = DAPR97; } Lender NEWPROVIDER38 = Lender.NONE; //inject NONSTANDARD NAMING if (MAX28 == CAPR5) { NEWPROVIDER38 = Lender.COMPOUND; } else if (MAX28 == IAPR100) { NEWPROVIDER38 = Lender.FULCRUM; } else if (MAX28 == AAPR96) { NEWPROVIDER38 = Lender.AAVE; } else if (MAX28 == DAPR97) { NEWPROVIDER38 = Lender.DYDX; } return NEWPROVIDER38; } function GETAAVE86() public view returns (address) { //inject NONSTANDARD NAMING return lendingpooladdressesprovider85(AAVE10).GETLENDINGPOOL88(); } function GETAAVECORE62() public view returns (address) { //inject NONSTANDARD NAMING return lendingpooladdressesprovider85(AAVE10).GETLENDINGPOOLCORE37(); } function APPROVETOKEN12() public { //inject NONSTANDARD NAMING ierc2093(TOKEN25).SAFEAPPROVE32(COMPOUND53, uint(-1)); ierc2093(TOKEN25).SAFEAPPROVE32(DYDX62, uint(-1)); ierc2093(TOKEN25).SAFEAPPROVE32(GETAAVECORE62(), uint(-1)); ierc2093(TOKEN25).SAFEAPPROVE32(FULCRUM19, uint(-1)); } function BALANCE62() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(TOKEN25).BALANCEOF25(address(this)); } function BALANCEDYDXAVAILABLE58() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(TOKEN25).BALANCEOF25(DYDX62); } function BALANCEDYDX47() public view returns (uint256) { //inject NONSTANDARD NAMING Wei memory BAL85 = dydx100(DYDX62).GETACCOUNTWEI65(Info(address(this), 0), DTOKEN6); //inject NONSTANDARD NAMING return BAL85.VALUE83; } function BALANCECOMPOUND27() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(COMPOUND53).BALANCEOF25(address(this)); } function BALANCECOMPOUNDINTOKEN38() public view returns (uint256) { //inject NONSTANDARD NAMING // Mantisa 1e18 to decimals uint256 B30 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING if (B30 > 0) { B30 = B30.MUL24(compound17(COMPOUND53).EXCHANGERATESTORED22()).DIV26(1e18); } return B30; } function BALANCEFULCRUMAVAILABLE62() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(CHAI29).BALANCEOF25(FULCRUM19); } function BALANCEFULCRUMINTOKEN93() public view returns (uint256) { //inject NONSTANDARD NAMING uint256 B30 = BALANCEFULCRUM60(); //inject NONSTANDARD NAMING if (B30 > 0) { B30 = fulcrum27(FULCRUM19).ASSETBALANCEOF38(address(this)); } return B30; } function BALANCEFULCRUM60() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(FULCRUM19).BALANCEOF25(address(this)); } function BALANCEAAVEAVAILABLE0() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(TOKEN25).BALANCEOF25(AAVEPOOL17); } function BALANCEAAVE23() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(AAVETOKEN8).BALANCEOF25(address(this)); } function REBALANCE91() public { //inject NONSTANDARD NAMING Lender NEWPROVIDER38 = RECOMMEND99(); //inject NONSTANDARD NAMING if (NEWPROVIDER38 != PROVIDER42) { _WITHDRAWALL34(); } if (BALANCE62() > 0) { if (NEWPROVIDER38 == Lender.DYDX) { _SUPPLYDYDX52(BALANCE62()); } else if (NEWPROVIDER38 == Lender.FULCRUM) { _SUPPLYFULCRUM48(BALANCE62()); } else if (NEWPROVIDER38 == Lender.COMPOUND) { _SUPPLYCOMPOUND47(BALANCE62()); } else if (NEWPROVIDER38 == Lender.AAVE) { _SUPPLYAAVE98(BALANCE62()); } } PROVIDER42 = NEWPROVIDER38; } function _WITHDRAWALL34() internal { //inject NONSTANDARD NAMING uint256 AMOUNT4 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING if (AMOUNT4 > 0) { _WITHDRAWSOMECOMPOUND30(BALANCECOMPOUNDINTOKEN38().SUB57(1)); } AMOUNT4 = BALANCEDYDX47(); if (AMOUNT4 > 0) { if (AMOUNT4 > BALANCEDYDXAVAILABLE58()) { AMOUNT4 = BALANCEDYDXAVAILABLE58(); } _WITHDRAWDYDX0(AMOUNT4); } AMOUNT4 = BALANCEFULCRUM60(); if (AMOUNT4 > 0) { if (AMOUNT4 > BALANCEFULCRUMAVAILABLE62().SUB57(1)) { AMOUNT4 = BALANCEFULCRUMAVAILABLE62().SUB57(1); } _WITHDRAWSOMEFULCRUM68(AMOUNT4); } AMOUNT4 = BALANCEAAVE23(); if (AMOUNT4 > 0) { if (AMOUNT4 > BALANCEAAVEAVAILABLE0()) { AMOUNT4 = BALANCEAAVEAVAILABLE0(); } _WITHDRAWAAVE10(AMOUNT4); } } function _WITHDRAWSOMECOMPOUND30(uint256 _AMOUNT50) internal { //inject NONSTANDARD NAMING uint256 B30 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING uint256 BT79 = BALANCECOMPOUNDINTOKEN38(); //inject NONSTANDARD NAMING require(BT79 >= _AMOUNT50, "insufficient funds"); // can have unintentional rounding errors uint256 AMOUNT4 = (B30.MUL24(_AMOUNT50)).DIV26(BT79).ADD27(1); //inject NONSTANDARD NAMING _WITHDRAWCOMPOUND82(AMOUNT4); } function _WITHDRAWSOMEFULCRUM68(uint256 _AMOUNT50) internal { //inject NONSTANDARD NAMING uint256 B30 = BALANCEFULCRUM60(); //inject NONSTANDARD NAMING uint256 BT79 = BALANCEFULCRUMINTOKEN93(); //inject NONSTANDARD NAMING require(BT79 >= _AMOUNT50, "insufficient funds"); // can have unintentional rounding errors uint256 AMOUNT4 = (B30.MUL24(_AMOUNT50)).DIV26(BT79).ADD27(1); //inject NONSTANDARD NAMING _WITHDRAWFULCRUM65(AMOUNT4); } function _WITHDRAWSOME38(uint256 _AMOUNT50) internal returns (bool) { //inject NONSTANDARD NAMING uint256 ORIGAMOUNT32 = _AMOUNT50; //inject NONSTANDARD NAMING uint256 AMOUNT4 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING if (AMOUNT4 > 0) { if (_AMOUNT50 > BALANCECOMPOUNDINTOKEN38().SUB57(1)) { _WITHDRAWSOMECOMPOUND30(BALANCECOMPOUNDINTOKEN38().SUB57(1)); _AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this))); } else { _WITHDRAWSOMECOMPOUND30(_AMOUNT50); return true; } } AMOUNT4 = BALANCEDYDX47(); if (AMOUNT4 > 0) { if (_AMOUNT50 > BALANCEDYDXAVAILABLE58()) { _WITHDRAWDYDX0(BALANCEDYDXAVAILABLE58()); _AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this))); } else { _WITHDRAWDYDX0(_AMOUNT50); return true; } } AMOUNT4 = BALANCEFULCRUM60(); if (AMOUNT4 > 0) { if (_AMOUNT50 > BALANCEFULCRUMAVAILABLE62().SUB57(1)) { AMOUNT4 = BALANCEFULCRUMAVAILABLE62().SUB57(1); _WITHDRAWSOMEFULCRUM68(BALANCEFULCRUMAVAILABLE62().SUB57(1)); _AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this))); } else { _WITHDRAWSOMEFULCRUM68(AMOUNT4); return true; } } AMOUNT4 = BALANCEAAVE23(); if (AMOUNT4 > 0) { if (_AMOUNT50 > BALANCEAAVEAVAILABLE0()) { _WITHDRAWAAVE10(BALANCEAAVEAVAILABLE0()); _AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this))); } else { _WITHDRAWAAVE10(_AMOUNT50); return true; } } return true; } function _SUPPLYDYDX52(uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING Info[] memory INFOS35 = new Info[](1); //inject NONSTANDARD NAMING INFOS35[0] = Info(address(this), 0); AssetAmount memory AMT17 = AssetAmount(true, AssetDenomination.Wei, AssetReference.Delta, AMOUNT4); //inject NONSTANDARD NAMING ActionArgs memory ACT61; //inject NONSTANDARD NAMING ACT61.ACTIONTYPE60 = ActionType.Deposit; ACT61.ACCOUNTID6 = 0; ACT61.AMOUNT4 = AMT17; ACT61.PRIMARYMARKETID93 = DTOKEN6; ACT61.OTHERADDRESS81 = address(this); ActionArgs[] memory ARGS40 = new ActionArgs[](1); //inject NONSTANDARD NAMING ARGS40[0] = ACT61; dydx100(DYDX62).OPERATE53(INFOS35, ARGS40); } function _SUPPLYAAVE98(uint AMOUNT4) internal { //inject NONSTANDARD NAMING aave60(GETAAVE86()).DEPOSIT43(TOKEN25, AMOUNT4, 0); } function _SUPPLYFULCRUM48(uint AMOUNT4) internal { //inject NONSTANDARD NAMING require(fulcrum27(FULCRUM19).MINT37(address(this), AMOUNT4) > 0, "FULCRUM: supply failed"); } function _SUPPLYCOMPOUND47(uint AMOUNT4) internal { //inject NONSTANDARD NAMING require(compound17(COMPOUND53).MINT37(AMOUNT4) == 0, "COMPOUND: supply failed"); } function _WITHDRAWAAVE10(uint AMOUNT4) internal { //inject NONSTANDARD NAMING atoken49(AAVETOKEN8).REDEEM71(AMOUNT4); } function _WITHDRAWFULCRUM65(uint AMOUNT4) internal { //inject NONSTANDARD NAMING require(fulcrum27(FULCRUM19).BURN1(address(this), AMOUNT4) > 0, "FULCRUM: withdraw failed"); } function _WITHDRAWCOMPOUND82(uint AMOUNT4) internal { //inject NONSTANDARD NAMING require(compound17(COMPOUND53).REDEEM71(AMOUNT4) == 0, "COMPOUND: withdraw failed"); } function _WITHDRAWDYDX0(uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING Info[] memory INFOS35 = new Info[](1); //inject NONSTANDARD NAMING INFOS35[0] = Info(address(this), 0); AssetAmount memory AMT17 = AssetAmount(false, AssetDenomination.Wei, AssetReference.Delta, AMOUNT4); //inject NONSTANDARD NAMING ActionArgs memory ACT61; //inject NONSTANDARD NAMING ACT61.ACTIONTYPE60 = ActionType.Withdraw; ACT61.ACCOUNTID6 = 0; ACT61.AMOUNT4 = AMT17; ACT61.PRIMARYMARKETID93 = DTOKEN6; ACT61.OTHERADDRESS81 = address(this); ActionArgs[] memory ARGS40 = new ActionArgs[](1); //inject NONSTANDARD NAMING ARGS40[0] = ACT61; dydx100(DYDX62).OPERATE53(INFOS35, ARGS40); } function CALCPOOLVALUEINTOKEN17() public view returns (uint) { //inject NONSTANDARD NAMING return BALANCECOMPOUNDINTOKEN38() .ADD27(BALANCEFULCRUMINTOKEN93()) .ADD27(BALANCEDYDX47()) .ADD27(BALANCEAAVE23()) .ADD27(BALANCE62()); } function GETPRICEPERFULLSHARE16() public view returns (uint) { //inject NONSTANDARD NAMING uint _POOL79 = CALCPOOLVALUEINTOKEN17(); //inject NONSTANDARD NAMING return _POOL79.MUL24(1e18).DIV26(_TOTALSUPPLY32); } }
inject NONSTANDARD NAMING
function BALANCEFULCRUMINTOKEN93() public view returns (uint256) {
7,220,537
[ 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, 225, 445, 605, 1013, 4722, 42, 1506, 5093, 2799, 3217, 6239, 11180, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: solidity-common/contracts/interface/IERC20.sol pragma solidity >=0.5.0 <0.7.0; /** * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md */ interface IERC20 { /** * 可选方法 */ function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * 必须方法 */ function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * 事件类型 */ event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/library/UQ112x112.sol pragma solidity >=0.5.0 <0.7.0; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) // range: [0, 2**112 - 1] // resolution: 1 / 2**112 library UQ112x112 { uint224 constant Q112 = 2 ** 112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } } // File: contracts/interface/IBtswapCallee.sol pragma solidity >=0.5.0 <0.7.0; interface IBtswapCallee { function bitswapCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external; } // File: contracts/interface/IBtswapFactory.sol pragma solidity >=0.5.0 <0.7.0; interface IBtswapFactory { function FEE_RATE_DENOMINATOR() external view returns (uint256); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function feeRateNumerator() external view returns (uint256); function initCodeHash() external view returns (bytes32); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setRouter(address) external; function setFeeTo(address) external; function setFeeToSetter(address) external; function setFeeRateNumerator(uint256) external; function setInitCodeHash(bytes32) external; function sortTokens(address tokenA, address tokenB) external pure returns (address token0, address token1); function pairFor(address factory, address tokenA, address tokenB) external view returns (address pair); function getReserves(address factory, address tokenA, address tokenB) external view returns (uint256 reserveA, uint256 reserveB); function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) external pure returns (uint256 amountB); function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) external view returns (uint256 amountOut); function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) external view returns (uint256 amountIn); function getAmountsOut(address factory, uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(address factory, uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); event PairCreated(address indexed token0, address indexed token1, address pair, uint256); } // File: contracts/interface/IBtswapPairToken.sol pragma solidity >=0.5.0 <0.7.0; interface IBtswapPairToken { function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function MINIMUM_LIQUIDITY() external pure returns (uint256); function router() external view returns (address); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address, address) external; function price(address token) external view returns (uint256); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to); event Swap(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to); event Sync(uint112 reserve0, uint112 reserve1); } // File: contracts/interface/IBtswapRouter02.sol pragma solidity >=0.5.0 <0.7.0; interface IBtswapRouter02 { function factory() external pure returns (address); function WETH() external pure returns (address); function BT() external pure returns (address); function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint256 amountA, uint256 amountB, uint256 liquidity); function addLiquidityETH(address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity); function removeLiquidity(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts); function swapTokensForExactTokens(uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts); function swapExactETHForTokens(uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external payable returns (uint256[] memory amounts); function swapTokensForExactETH(uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts); function swapExactTokensForETH(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts); function swapETHForExactTokens(uint256 amountOut, address[] calldata path, address to, uint256 deadline) external payable returns (uint256[] memory amounts); function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) external view returns (uint256 amountB); function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) external view returns (uint256 amountOut); function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) external view returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function removeLiquidityETHSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external; function swapExactETHForTokensSupportingFeeOnTransferTokens(uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external; function weth(address token) external view returns (uint256); function onTransfer(address sender, address recipient) external returns (bool); } // File: solidity-common/contracts/library/SafeMath.sol pragma solidity >=0.5.0 <0.7.0; /** * 算术操作 */ library SafeMath { uint256 constant WAD = 10 ** 18; uint256 constant RAY = 10 ** 27; function wad() public pure returns (uint256) { return WAD; } function ray() public pure returns (uint256) { return RAY; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function 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; } 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; } function sqrt(uint256 a) internal pure returns (uint256 b) { if (a > 3) { b = a; uint256 x = a / 2 + 1; while (x < b) { b = x; x = (a / x + x) / 2; } } else if (a != 0) { b = 1; } } function wmul(uint256 a, uint256 b) internal pure returns (uint256) { return mul(a, b) / WAD; } function wmulRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, b), WAD / 2) / WAD; } function rmul(uint256 a, uint256 b) internal pure returns (uint256) { return mul(a, b) / RAY; } function rmulRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, b), RAY / 2) / RAY; } function wdiv(uint256 a, uint256 b) internal pure returns (uint256) { return div(mul(a, WAD), b); } function wdivRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, WAD), b / 2) / b; } function rdiv(uint256 a, uint256 b) internal pure returns (uint256) { return div(mul(a, RAY), b); } function rdivRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, RAY), b / 2) / b; } function wpow(uint256 x, uint256 n) internal pure returns (uint256) { uint256 result = WAD; while (n > 0) { if (n % 2 != 0) { result = wmul(result, x); } x = wmul(x, x); n /= 2; } return result; } function rpow(uint256 x, uint256 n) internal pure returns (uint256) { uint256 result = RAY; while (n > 0) { if (n % 2 != 0) { result = rmul(result, x); } x = rmul(x, x); n /= 2; } return result; } } // File: contracts/interface/IBtswapERC20.sol pragma solidity >=0.5.0 <0.7.0; interface IBtswapERC20 { function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); } // File: contracts/biz/BtswapERC20.sol pragma solidity >=0.5.0 <0.7.0; contract BtswapERC20 is IBtswapERC20 { using SafeMath for uint256; string public constant name = "Btswap Pair Token"; string public constant symbol = "BPT"; uint8 public constant decimals = 18; uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; mapping(address => uint256) public nonces; bytes32 public DOMAIN_SEPARATOR; bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; constructor() public { uint256 chainId; assembly { chainId := chainid } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes("1")), chainId, address(this) ) ); } function _mint(address to, uint256 value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint256 value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint256 value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint256 value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint256 value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { if (allowance[from][msg.sender] != uint256(- 1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, "BtswapPairToken: EXPIRED"); 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, "BtswapPairToken: INVALID_SIGNATURE"); _approve(owner, spender, value); } event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); } // File: contracts/biz/BtswapPairToken.sol pragma solidity >=0.5.0 <0.7.0; contract BtswapPairToken is IBtswapPairToken, BtswapERC20 { using SafeMath for uint256; using UQ112x112 for uint224; uint256 public constant MINIMUM_LIQUIDITY = 10 ** 3; bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)"))); address public router; address public factory; address public token0; address public token1; uint256 private unlocked = 1; uint112 private reserve0; // uses single storage slot, accessible via getReserves uint112 private reserve1; // uses single storage slot, accessible via getReserves uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves uint256 public price0CumulativeLast; uint256 public price1CumulativeLast; uint256 public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event constructor() public { factory = msg.sender; } // called once by the factory at time of deployment function initialize(address _router, address _token0, address _token1) external { // sufficient check require(msg.sender == factory, "BtswapPairToken: FORBIDDEN"); router = _router; token0 = _token0; token1 = _token1; } // update reserves and, on the first call per block, price accumulators function _update(uint256 balance0, uint256 balance1, uint112 _reserve0, uint112 _reserve1) private { require(balance0 <= uint112(- 1) && balance1 <= uint112(- 1), "BtswapPairToken: OVERFLOW"); uint32 blockTimestamp = uint32(block.timestamp % 2 ** 32); // overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { // * never overflows, and + overflow is desired price0CumulativeLast += uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); } // if fee is on, mint liquidity equivalent to 1/5th of the growth in sqrt(k) function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = IBtswapFactory(factory).feeTo(); feeOn = feeTo != address(0); // gas savings uint256 _kLast = kLast; if (feeOn) { if (_kLast != 0) { uint256 rootK = SafeMath.sqrt(uint256(_reserve0).mul(_reserve1)); uint256 rootKLast = SafeMath.sqrt(_kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply.mul(rootK.sub(rootKLast)); uint256 denominator = rootK.mul(4).add(rootKLast); uint256 liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (_kLast != 0) { kLast = 0; } } // this low-level function should be called from a contract which performs important safety checks function mint(address to) external lock returns (uint256 liquidity) { require(msg.sender == router, "BtswapPairToken: FORBIDDEN"); // gas savings (uint112 _reserve0, uint112 _reserve1,) = getReserves(); uint256 balance0 = IERC20(token0).balanceOf(address(this)); uint256 balance1 = IERC20(token1).balanceOf(address(this)); uint256 amount0 = balance0.sub(_reserve0); uint256 amount1 = balance1.sub(_reserve1); bool feeOn = _mintFee(_reserve0, _reserve1); // gas savings, must be defined here since totalSupply can update in _mintFee uint256 _totalSupply = totalSupply; if (_totalSupply == 0) { liquidity = SafeMath.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens _mint(address(0), MINIMUM_LIQUIDITY); } else { liquidity = SafeMath.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } require(liquidity > 0, "BtswapPairToken: INSUFFICIENT_LIQUIDITY_MINTED"); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); // reserve0 and reserve1 are up-to-date if (feeOn) kLast = uint256(reserve0).mul(reserve1); emit Mint(msg.sender, amount0, amount1); } // this low-level function should be called from a contract which performs important safety checks function burn(address to) external lock returns (uint256 amount0, uint256 amount1) { require(msg.sender == router, "BtswapPairToken: FORBIDDEN"); // gas savings (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings address _token0 = token0; // gas savings address _token1 = token1; uint256 balance0 = IERC20(_token0).balanceOf(address(this)); uint256 balance1 = IERC20(_token1).balanceOf(address(this)); uint256 liquidity = balanceOf[address(this)]; bool feeOn = _mintFee(_reserve0, _reserve1); // gas savings, must be defined here since totalSupply can update in _mintFee uint256 _totalSupply = totalSupply; // using balances ensures pro-rata distribution amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution amount1 = liquidity.mul(balance1) / _totalSupply; require(amount0 > 0 && amount1 > 0, "BtswapPairToken: INSUFFICIENT_LIQUIDITY_BURNED"); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); _update(balance0, balance1, _reserve0, _reserve1); // reserve0 and reserve1 are up-to-date if (feeOn) kLast = uint256(reserve0).mul(reserve1); emit Burn(msg.sender, amount0, amount1, to); } // this low-level function should be called from a contract which performs important safety checks function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external lock { require(msg.sender == router, "BtswapPairToken: FORBIDDEN"); require(amount0Out > 0 || amount1Out > 0, "BtswapPairToken: INSUFFICIENT_OUTPUT_AMOUNT"); // gas savings (uint112 _reserve0, uint112 _reserve1,) = getReserves(); require(amount0Out < _reserve0 && amount1Out < _reserve1, "BtswapPairToken: INSUFFICIENT_LIQUIDITY"); uint256 balance0; uint256 balance1; {// scope for _token{0,1}, avoids stack too deep errors address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, "BtswapPairToken: INVALID_TO"); // optimistically transfer tokens if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); if (data.length > 0) IBtswapCallee(to).bitswapCall(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); } uint256 amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint256 amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, "BtswapPairToken: INSUFFICIENT_INPUT_AMOUNT"); {// scope for reserve{0,1}Adjusted, avoids stack too deep errors uint256 balance0Adjusted = balance0.mul(1e4).sub(amount0In.mul(IBtswapFactory(factory).feeRateNumerator())); uint256 balance1Adjusted = balance1.mul(1e4).sub(amount1In.mul(IBtswapFactory(factory).feeRateNumerator())); require(balance0Adjusted.mul(balance1Adjusted) >= uint256(_reserve0).mul(_reserve1).mul(1e8), "BtswapPairToken: K"); } _update(balance0, balance1, _reserve0, _reserve1); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); } // force balances to match reserves function skim(address to) external lock { // gas savings address _token0 = token0; // gas savings address _token1 = token1; _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0)); _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1)); } // force reserves to match balances function sync() external lock { _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1); } function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) { _reserve0 = reserve0; _reserve1 = reserve1; _blockTimestampLast = blockTimestampLast; } function _safeTransfer(address token, address to, uint256 value) private { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BtswapPairToken: TRANSFER_FAILED"); } function price(address token) public view returns (uint256) { if ((token0 != token && token1 != token) || 0 == reserve0 || 0 == reserve1) { return 0; } if (token0 == token) { return SafeMath.wad().mul(reserve1).div(reserve0); } else { return SafeMath.wad().mul(reserve0).div(reserve1); } } function transfer(address to, uint256 value) public returns (bool) { super.transfer(to, value); return IBtswapRouter02(router).onTransfer(msg.sender, to); } function transferFrom(address from, address to, uint256 value) public returns (bool) { super.transferFrom(from, to, value); if (msg.sender == router) { return true; } return IBtswapRouter02(router).onTransfer(from, to); } modifier lock() { require(unlocked == 1, "BtswapPairToken: LOCKED"); unlocked = 0; _; unlocked = 1; } event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to); event Swap(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to); event Sync(uint112 reserve0, uint112 reserve1); }
update reserves and, on the first call per block, price accumulators overflow is desired * never overflows, and + overflow is desired
function _update(uint256 balance0, uint256 balance1, uint112 _reserve0, uint112 _reserve1) private { require(balance0 <= uint112(- 1) && balance1 <= uint112(- 1), "BtswapPairToken: OVERFLOW"); uint32 blockTimestamp = uint32(block.timestamp % 2 ** 32); uint32 timeElapsed = blockTimestamp - blockTimestampLast; if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { price0CumulativeLast += uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); }
1,570,135
[ 1, 2725, 400, 264, 3324, 471, 16, 603, 326, 1122, 745, 1534, 1203, 16, 6205, 8822, 3062, 9391, 353, 6049, 225, 5903, 9391, 87, 16, 471, 397, 9391, 353, 6049, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2725, 12, 11890, 5034, 11013, 20, 16, 2254, 5034, 11013, 21, 16, 2254, 17666, 389, 455, 6527, 20, 16, 2254, 17666, 389, 455, 6527, 21, 13, 3238, 288, 203, 3639, 2583, 12, 12296, 20, 1648, 2254, 17666, 19236, 404, 13, 597, 11013, 21, 1648, 2254, 17666, 19236, 404, 3631, 315, 38, 3428, 91, 438, 4154, 1345, 30, 22577, 17430, 8863, 203, 3639, 2254, 1578, 1203, 4921, 273, 2254, 1578, 12, 2629, 18, 5508, 738, 576, 2826, 3847, 1769, 203, 3639, 2254, 1578, 813, 28827, 273, 1203, 4921, 300, 1203, 4921, 3024, 31, 203, 3639, 309, 261, 957, 28827, 405, 374, 597, 389, 455, 6527, 20, 480, 374, 597, 389, 455, 6527, 21, 480, 374, 13, 288, 203, 5411, 6205, 20, 39, 11276, 3024, 1011, 2254, 5034, 12, 57, 53, 17666, 92, 17666, 18, 3015, 24899, 455, 6527, 21, 2934, 89, 85, 2892, 24899, 455, 6527, 20, 3719, 380, 813, 28827, 31, 203, 5411, 6205, 21, 39, 11276, 3024, 1011, 2254, 5034, 12, 57, 53, 17666, 92, 17666, 18, 3015, 24899, 455, 6527, 20, 2934, 89, 85, 2892, 24899, 455, 6527, 21, 3719, 380, 813, 28827, 31, 203, 3639, 289, 203, 3639, 20501, 20, 273, 2254, 17666, 12, 12296, 20, 1769, 203, 3639, 20501, 21, 273, 2254, 17666, 12, 12296, 21, 1769, 203, 3639, 1203, 4921, 3024, 273, 1203, 4921, 31, 203, 3639, 3626, 9721, 12, 455, 6527, 20, 16, 20501, 21, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /* ____ _______ ________ __________ _ ____________ ____ __ / __ \/ ____/ | / /_ __/ / ____/ __ \/ | / /_ __/ __ \/ __ \/ / / /_/ / __/ / |/ / / / / / / / / / |/ / / / / /_/ / / / / / / _, _/ /___/ /| / / / / /___/ /_/ / /| / / / / _, _/ /_/ / /___ /_/ |_/_____/_/ |_/ /_/ \____/\____/_/ |_/ /_/ /_/ |_|\____/_____/ website: https://rentcontrol.tk discord: https://discord.gg/X78kgWp Buy Property. Collect Rent. Rent Control is a strategy game where you buy property levels and collect rent from other owners. Game begins with 20 property levels. Level 1 is the best and most valuable. When you own a property level, you collect rent from the purchases of every other level. Different levels have different rates of rent. Level 1 collects 10% of all rent distributions from each purchase. Once you buy a property level it is then available for purchase at a price 10% higher than what you paid. So you will earn rent while you won the property AND you will have a capital gain when someone buys the level from you. Property owner receives 50% of the gain from a sale. 30% of gains are distributed to other property owners based on their rates of rent. 20% of gains are distributed to dev. Masternodes recieve 5% of any distributions from buyers using the link. */ contract RENTCONTROL { /*================================= = MODIFIERS = =================================*/ modifier onlyOwner(){ require(msg.sender == dev); _; } /*============================== = EVENTS = ==============================*/ event onLevelPurchase( address customerAddress, uint256 incomingEthereum, uint256 level, uint256 newPrice ); event onWithdraw( address customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address from, address to, uint256 level ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "RENT CONTROL"; string public symbol = "LEVEL"; uint8 constant public devDivRate = 20; uint8 constant public ownerDivRate = 50; uint8 constant public distDivRate = 30; uint8 constant public referralRate = 5; uint8 constant public decimals = 18; uint public totalLevelValue = 2465e16; /*================================ = DATASETS = ================================*/ mapping(uint => address) internal levelOwner; mapping(uint => uint) public levelPrice; mapping(uint => uint) internal levelPreviousPrice; mapping(address => uint) internal ownerAccounts; mapping(uint => uint) internal totalLevelDivs; mapping(uint => string) internal levelName; uint levelPriceIncrement = 110; uint totalDivsProduced = 0; uint public maxLevels = 200; uint public initialPrice = 5e16; //0.05 ETH uint public nextAvailableLevel; bool allowReferral = false; bool allowAutoNewLevel = false; address dev; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function RENTCONTROL() public { dev = msg.sender; nextAvailableLevel = 21; levelOwner[1] = dev; levelPrice[1] = 5e18; levelPreviousPrice[1] = levelPrice[1]; levelOwner[2] = dev; levelPrice[2] = 4e18; levelPreviousPrice[2] = levelPrice[2]; levelOwner[3] = dev; levelPrice[3] = 3e18; levelPreviousPrice[3] = levelPrice[3]; levelOwner[4] = dev; levelPrice[4] = 25e17; levelPreviousPrice[4] = levelPrice[4]; levelOwner[5] = dev; levelPrice[5] = 20e17; levelPreviousPrice[5] = levelPrice[5]; levelOwner[6] = dev; levelPrice[6] = 15e17; levelPreviousPrice[6] = levelPrice[6]; levelOwner[7] = dev; levelPrice[7] = 125e16; levelPreviousPrice[7] = levelPrice[7]; levelOwner[8] = dev; levelPrice[8] = 100e16; levelPreviousPrice[8] = levelPrice[8]; levelOwner[9] = dev; levelPrice[9] = 80e16; levelPreviousPrice[9] = levelPrice[9]; levelOwner[10] = dev; levelPrice[10] = 70e16; levelPreviousPrice[10] = levelPrice[10]; levelOwner[11] = dev; levelPrice[11] = 60e16; levelPreviousPrice[11] = levelPrice[11]; levelOwner[12] = dev; levelPrice[12] = 50e16; levelPreviousPrice[12] = levelPrice[12]; levelOwner[13] = dev; levelPrice[13] = 40e16; levelPreviousPrice[13] = levelPrice[13]; levelOwner[14] = dev; levelPrice[14] = 35e16; levelPreviousPrice[14] = levelPrice[14]; levelOwner[15] = dev; levelPrice[15] = 30e16; levelPreviousPrice[15] = levelPrice[15]; levelOwner[16] = dev; levelPrice[16] = 25e16; levelPreviousPrice[16] = levelPrice[16]; levelOwner[17] = dev; levelPrice[17] = 20e16; levelPreviousPrice[17] = levelPrice[17]; levelOwner[18] = dev; levelPrice[18] = 15e16; levelPreviousPrice[18] = levelPrice[18]; levelOwner[19] = dev; levelPrice[19] = 10e16; levelPreviousPrice[19] = levelPrice[19]; levelOwner[20] = dev; levelPrice[20] = 5e16; levelPreviousPrice[20] = levelPrice[20]; } function addTotalLevelValue(uint _new, uint _old) internal { uint newPrice = SafeMath.div(SafeMath.mul(_new,levelPriceIncrement),100); totalLevelValue = SafeMath.add(totalLevelValue, SafeMath.sub(newPrice,_old)); } function buy(uint _level, address _referrer) public payable { require(_level <= nextAvailableLevel); require(msg.value >= levelPrice[_level]); addTotalLevelValue(msg.value, levelPreviousPrice[_level]); if (levelOwner[_level] == dev){ require(msg.value >= levelPrice[_level]); // uint _price = msg.value; if ((allowAutoNewLevel) && (_level == nextAvailableLevel - 1) && nextAvailableLevel < maxLevels) { levelOwner[nextAvailableLevel] = dev; levelPrice[nextAvailableLevel] = initialPrice; nextAvailableLevel = nextAvailableLevel + 1; } ownerAccounts[dev] = SafeMath.add(ownerAccounts[dev],msg.value); levelOwner[_level] = msg.sender; //Increment the Level Price levelPreviousPrice[_level] = msg.value; levelPrice[_level] = SafeMath.div(SafeMath.mul(msg.value,levelPriceIncrement),100); //levelName[_level] = _name; //Give your level an optional name } else { require(msg.sender != levelOwner[_level]); // uint _price = msg.value; uint _newPrice = SafeMath.div(SafeMath.mul(msg.value,levelPriceIncrement),100); //Determine the total dividends uint _baseDividends = msg.value - levelPreviousPrice[_level]; totalDivsProduced = SafeMath.add(totalDivsProduced, _baseDividends); uint _devDividends = SafeMath.div(SafeMath.mul(_baseDividends,devDivRate),100); uint _ownerDividends = SafeMath.div(SafeMath.mul(_baseDividends,ownerDivRate),100); totalLevelDivs[_level] = SafeMath.add(totalLevelDivs[_level],_ownerDividends); _ownerDividends = SafeMath.add(_ownerDividends,levelPreviousPrice[_level]); uint _distDividends = SafeMath.div(SafeMath.mul(_baseDividends,distDivRate),100); if (allowReferral && (_referrer != msg.sender) && (_referrer != 0x0000000000000000000000000000000000000000)) { uint _referralDividends = SafeMath.div(SafeMath.mul(_baseDividends,referralRate),100); _distDividends = SafeMath.sub(_distDividends,_referralDividends); ownerAccounts[_referrer] = SafeMath.add(ownerAccounts[_referrer],_referralDividends); } //distribute dividends to accounts address _previousOwner = levelOwner[_level]; address _newOwner = msg.sender; ownerAccounts[_previousOwner] = SafeMath.add(ownerAccounts[_previousOwner],_ownerDividends); ownerAccounts[dev] = SafeMath.add(ownerAccounts[dev],_devDividends); distributeRent(nextAvailableLevel, _distDividends); //Increment the Level Price levelPreviousPrice[_level] = msg.value; levelPrice[_level] = _newPrice; levelOwner[_level] = _newOwner; //levelName[_level] = _name; //Give your level an optional name } emit onLevelPurchase(msg.sender, msg.value, _level, SafeMath.div(SafeMath.mul(msg.value,levelPriceIncrement),100)); } function distributeRent(uint _levels, uint _distDividends) { uint _distFactor = 10; uint counter = 1; ownerAccounts[dev] = SafeMath.add(ownerAccounts[dev], _distDividends); while (counter < nextAvailableLevel) { uint _distAmountLocal = SafeMath.div(_distDividends,_distFactor); ownerAccounts[levelOwner[counter]] = SafeMath.add(ownerAccounts[levelOwner[counter]],_distAmountLocal); totalLevelDivs[counter] = SafeMath.add(totalLevelDivs[counter],_distAmountLocal); counter = counter + 1; ownerAccounts[dev] = SafeMath.sub(ownerAccounts[dev], _distAmountLocal); _distFactor = SafeMath.div(SafeMath.mul(_distFactor, 112),100); } } function withdraw() public { address _customerAddress = msg.sender; require(ownerAccounts[_customerAddress] > 0); uint _dividends = ownerAccounts[_customerAddress]; ownerAccounts[_customerAddress] = 0; _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } function withdrawPart(uint _amount) public onlyOwner() { address _customerAddress = msg.sender; require(ownerAccounts[_customerAddress] > 0); require(_amount <= ownerAccounts[_customerAddress]); ownerAccounts[_customerAddress] = SafeMath.sub(ownerAccounts[_customerAddress],_amount); _customerAddress.transfer(_amount); // fire event onWithdraw(_customerAddress, _amount); } // Fallback function: just send funds back function() payable public { revert(); } /** * Transfer Level to another address */ function transfer(address _to, uint _level ) public { require(levelOwner[nextAvailableLevel] == msg.sender); levelOwner[nextAvailableLevel] = _to; emit Transfer(msg.sender, _to, _level); } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** /** * If we want to rebrand, we can. */ function setName(string _name) onlyOwner() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyOwner() public { symbol = _symbol; } function setInitialPrice(uint _price) onlyOwner() public { initialPrice = _price; } function setMaxLevels(uint _level) onlyOwner() public { maxLevels = _level; } function setLevelPrice(uint _level, uint _price) //Allow the changing of a level price owner if the dev owns it onlyOwner() public { require(levelOwner[_level] == dev); levelPrice[_level] = _price; } function addNewLevel(uint _price) onlyOwner() public { require(nextAvailableLevel < maxLevels); levelPrice[nextAvailableLevel] = _price; levelOwner[nextAvailableLevel] = dev; totalLevelDivs[nextAvailableLevel] = 0; nextAvailableLevel = nextAvailableLevel + 1; } function setAllowReferral(bool _allowReferral) onlyOwner() public { allowReferral = _allowReferral; } function setAutoNewlevel(bool _autoNewLevel) onlyOwner() public { allowAutoNewLevel = _autoNewLevel; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function getMyBalance() public view returns(uint) { return ownerAccounts[msg.sender]; } function getOwnerBalance(address _levelOwner) public view returns(uint) { require(msg.sender == dev); return ownerAccounts[_levelOwner]; } function getlevelPrice(uint _level) public view returns(uint) { require(_level <= nextAvailableLevel); return levelPrice[_level]; } function getlevelOwner(uint _level) public view returns(address) { require(_level <= nextAvailableLevel); return levelOwner[_level]; } function gettotalLevelDivs(uint _level) public view returns(uint) { require(_level <= nextAvailableLevel); return totalLevelDivs[_level]; } function getTotalDivsProduced() public view returns(uint) { return totalDivsProduced; } function getTotalLevelValue() public view returns(uint) { return totalLevelValue; } function totalEthereumBalance() public view returns(uint) { return address (this).balance; } function getNextAvailableLevel() public view returns(uint) { return nextAvailableLevel; } } /** * @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; } }
* Transfer Level to another address/
function transfer(address _to, uint _level ) public { require(levelOwner[nextAvailableLevel] == msg.sender); levelOwner[nextAvailableLevel] = _to; emit Transfer(msg.sender, _to, _level); }
12,652,191
[ 1, 5912, 4557, 358, 4042, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 389, 2815, 262, 203, 3639, 203, 3639, 1071, 203, 565, 288, 203, 3639, 2583, 12, 2815, 5541, 63, 4285, 5268, 2355, 65, 422, 1234, 18, 15330, 1769, 203, 203, 3639, 1801, 5541, 63, 4285, 5268, 2355, 65, 273, 389, 869, 31, 203, 203, 3639, 3626, 12279, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 2815, 1769, 203, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-04-02 */ /** *Submitted for verification at Etherscan.io on 2020-11-11 */ /** *Submitted for verification at Etherscan.io on 2020-02-28 */ /** *Submitted for verification at Etherscan.io on 2020-01-11 */ pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { using SafeMath for uint256; uint256 internal constant WAD = 1e18; uint256 internal constant halfWAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant halfRAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @return one ray, 1e27 **/ function ray() internal pure returns (uint256) { return RAY; } /** * @return one wad, 1e18 **/ function wad() internal pure returns (uint256) { return WAD; } /** * @return half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return halfRAY; } /** * @return half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return halfWAD; } /** * @dev multiplies two wad, rounding half up to the nearest wad * @param a wad * @param b wad * @return the result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { return halfWAD.add(a.mul(b)).div(WAD); } /** * @dev divides two wad, rounding half up to the nearest wad * @param a wad * @param b wad * @return the result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { uint256 halfB = b / 2; return halfB.add(a.mul(WAD)).div(b); } /** * @dev multiplies two ray, rounding half up to the nearest ray * @param a ray * @param b ray * @return the result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { return halfRAY.add(a.mul(b)).div(RAY); } /** * @dev divides two ray, rounding half up to the nearest ray * @param a ray * @param b ray * @return the result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { uint256 halfB = b / 2; return halfB.add(a.mul(RAY)).div(b); } /** * @dev casts ray down to wad * @param a ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; return halfRatio.add(a).div(WAD_RAY_RATIO); } /** * @dev convert wad up to ray * @param a wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { return a.mul(WAD_RAY_RATIO); } /** * @dev calculates base^exp. The code uses the ModExp precompile * @return base^exp, in ray */ //solium-disable-next-line function rayPow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rayMul(x, x); if (n % 2 != 0) { z = rayMul(z, x); } } } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier * available, which can be aplied 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. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @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() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an `Approval` event is emitted on calls to `transferFrom`. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard `decreaseAllowance` and `increaseAllowance` * functions have been added to mitigate the well-known issues around setting * allowances. See `IERC20.approve`. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `amount` tokens from `account`, reducing the * total supply. * * Emits a `Transfer` event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that 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; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @title VersionedInitializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. * * @author Aave, inspired by the OpenZeppelin Initializable contract */ contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 private lastInitializedRevision = 0; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(initializing || isConstructor() || revision > lastInitializedRevision, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; lastInitializedRevision = revision; } _; if (isTopLevelCall) { initializing = false; } } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure returns(uint256); /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; //solium-disable-next-line assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ function() external payable { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { //solium-disable-next-line 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 Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal {} /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @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 Returns the current implementation. * @return Address of the current implementation */ function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; //solium-disable-next-line assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require( Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address" ); bytes32 slot = IMPLEMENTATION_SLOT; //solium-disable-next-line assembly { sstore(slot, newImplementation) } } } /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @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 Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); (bool success, ) = newImplementation.delegatecall(data); require(success); } /** * @return The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; //solium-disable-next-line assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; //solium-disable-next-line assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } } /** * @title UpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } /** * @title AdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for * initializing the implementation, admin, and init data. */ contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, address _admin, bytes memory _data) public payable UpgradeabilityProxy(_logic, _data) { assert(ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(_admin); } } /** * @title InitializableUpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing * implementation and init data. */ contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } contract AddressStorage { mapping(bytes32 => address) private addresses; function getAddress(bytes32 _key) public view returns (address) { return addresses[_key]; } function _setAddress(bytes32 _key, address _value) internal { addresses[_key] = _value; } } /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for * initializing the implementation, admin, and init data. */ contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * Contract initializer. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, address _admin, bytes memory _data) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(_logic, _data); assert(ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(_admin); } } /** @title ILendingPoolAddressesProvider interface @notice provides the interface to fetch the LendingPoolCore address */ contract ILendingPoolAddressesProvider { function getLendingPool() public view returns (address); function setLendingPoolImpl(address _pool) public; function getLendingPoolCore() public view returns (address payable); function setLendingPoolCoreImpl(address _lendingPoolCore) public; function getLendingPoolConfigurator() public view returns (address); function setLendingPoolConfiguratorImpl(address _configurator) public; function getLendingPoolDataProvider() public view returns (address); function setLendingPoolDataProviderImpl(address _provider) public; function getLendingPoolParametersProvider() public view returns (address); function setLendingPoolParametersProviderImpl(address _parametersProvider) public; function getTokenDistributor() public view returns (address); function setTokenDistributor(address _tokenDistributor) public; function getFeeProvider() public view returns (address); function setFeeProviderImpl(address _feeProvider) public; function getLendingPoolLiquidationManager() public view returns (address); function setLendingPoolLiquidationManager(address _manager) public; function getLendingPoolManager() public view returns (address); function setLendingPoolManager(address _lendingPoolManager) public; function getPriceOracle() public view returns (address); function setPriceOracle(address _priceOracle) public; function getLendingRateOracle() public view returns (address); function setLendingRateOracle(address _lendingRateOracle) public; } /** * @title LendingPoolAddressesProvider contract * @notice Is the main registry of the protocol. All the different components of the protocol are accessible * through the addresses provider. * @author Aave **/ contract LendingPoolAddressesProvider is Ownable, ILendingPoolAddressesProvider, AddressStorage { //events event LendingPoolUpdated(address indexed newAddress); event LendingPoolCoreUpdated(address indexed newAddress); event LendingPoolParametersProviderUpdated(address indexed newAddress); event LendingPoolManagerUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolLiquidationManagerUpdated(address indexed newAddress); event LendingPoolDataProviderUpdated(address indexed newAddress); event EthereumAddressUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event FeeProviderUpdated(address indexed newAddress); event TokenDistributorUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); bytes32 private constant LENDING_POOL = "LENDING_POOL"; bytes32 private constant LENDING_POOL_CORE = "LENDING_POOL_CORE"; bytes32 private constant LENDING_POOL_CONFIGURATOR = "LENDING_POOL_CONFIGURATOR"; bytes32 private constant LENDING_POOL_PARAMETERS_PROVIDER = "PARAMETERS_PROVIDER"; bytes32 private constant LENDING_POOL_MANAGER = "LENDING_POOL_MANAGER"; bytes32 private constant LENDING_POOL_LIQUIDATION_MANAGER = "LIQUIDATION_MANAGER"; bytes32 private constant LENDING_POOL_FLASHLOAN_PROVIDER = "FLASHLOAN_PROVIDER"; bytes32 private constant DATA_PROVIDER = "DATA_PROVIDER"; bytes32 private constant ETHEREUM_ADDRESS = "ETHEREUM_ADDRESS"; bytes32 private constant PRICE_ORACLE = "PRICE_ORACLE"; bytes32 private constant LENDING_RATE_ORACLE = "LENDING_RATE_ORACLE"; bytes32 private constant FEE_PROVIDER = "FEE_PROVIDER"; bytes32 private constant WALLET_BALANCE_PROVIDER = "WALLET_BALANCE_PROVIDER"; bytes32 private constant TOKEN_DISTRIBUTOR = "TOKEN_DISTRIBUTOR"; /** * @dev returns the address of the LendingPool proxy * @return the lending pool proxy address **/ function getLendingPool() public view returns (address) { return getAddress(LENDING_POOL); } /** * @dev updates the implementation of the lending pool * @param _pool the new lending pool implementation **/ function setLendingPoolImpl(address _pool) public onlyOwner { updateImplInternal(LENDING_POOL, _pool); emit LendingPoolUpdated(_pool); } /** * @dev returns the address of the LendingPoolCore proxy * @return the lending pool core proxy address */ function getLendingPoolCore() public view returns (address payable) { address payable core = address(uint160(getAddress(LENDING_POOL_CORE))); return core; } /** * @dev updates the implementation of the lending pool core * @param _lendingPoolCore the new lending pool core implementation **/ function setLendingPoolCoreImpl(address _lendingPoolCore) public onlyOwner { updateImplInternal(LENDING_POOL_CORE, _lendingPoolCore); emit LendingPoolCoreUpdated(_lendingPoolCore); } /** * @dev returns the address of the LendingPoolConfigurator proxy * @return the lending pool configurator proxy address **/ function getLendingPoolConfigurator() public view returns (address) { return getAddress(LENDING_POOL_CONFIGURATOR); } /** * @dev updates the implementation of the lending pool configurator * @param _configurator the new lending pool configurator implementation **/ function setLendingPoolConfiguratorImpl(address _configurator) public onlyOwner { updateImplInternal(LENDING_POOL_CONFIGURATOR, _configurator); emit LendingPoolConfiguratorUpdated(_configurator); } /** * @dev returns the address of the LendingPoolDataProvider proxy * @return the lending pool data provider proxy address */ function getLendingPoolDataProvider() public view returns (address) { return getAddress(DATA_PROVIDER); } /** * @dev updates the implementation of the lending pool data provider * @param _provider the new lending pool data provider implementation **/ function setLendingPoolDataProviderImpl(address _provider) public onlyOwner { updateImplInternal(DATA_PROVIDER, _provider); emit LendingPoolDataProviderUpdated(_provider); } /** * @dev returns the address of the LendingPoolParametersProvider proxy * @return the address of the Lending pool parameters provider proxy **/ function getLendingPoolParametersProvider() public view returns (address) { return getAddress(LENDING_POOL_PARAMETERS_PROVIDER); } /** * @dev updates the implementation of the lending pool parameters provider * @param _parametersProvider the new lending pool parameters provider implementation **/ function setLendingPoolParametersProviderImpl(address _parametersProvider) public onlyOwner { updateImplInternal(LENDING_POOL_PARAMETERS_PROVIDER, _parametersProvider); emit LendingPoolParametersProviderUpdated(_parametersProvider); } /** * @dev returns the address of the FeeProvider proxy * @return the address of the Fee provider proxy **/ function getFeeProvider() public view returns (address) { return getAddress(FEE_PROVIDER); } /** * @dev updates the implementation of the FeeProvider proxy * @param _feeProvider the new lending pool fee provider implementation **/ function setFeeProviderImpl(address _feeProvider) public onlyOwner { updateImplInternal(FEE_PROVIDER, _feeProvider); emit FeeProviderUpdated(_feeProvider); } /** * @dev returns the address of the LendingPoolLiquidationManager. Since the manager is used * through delegateCall within the LendingPool contract, the proxy contract pattern does not work properly hence * the addresses are changed directly. * @return the address of the Lending pool liquidation manager **/ function getLendingPoolLiquidationManager() public view returns (address) { return getAddress(LENDING_POOL_LIQUIDATION_MANAGER); } /** * @dev updates the address of the Lending pool liquidation manager * @param _manager the new lending pool liquidation manager address **/ function setLendingPoolLiquidationManager(address _manager) public onlyOwner { _setAddress(LENDING_POOL_LIQUIDATION_MANAGER, _manager); emit LendingPoolLiquidationManagerUpdated(_manager); } /** * @dev the functions below are storing specific addresses that are outside the context of the protocol * hence the upgradable proxy pattern is not used **/ function getLendingPoolManager() public view returns (address) { return getAddress(LENDING_POOL_MANAGER); } function setLendingPoolManager(address _lendingPoolManager) public onlyOwner { _setAddress(LENDING_POOL_MANAGER, _lendingPoolManager); emit LendingPoolManagerUpdated(_lendingPoolManager); } function getPriceOracle() public view returns (address) { return getAddress(PRICE_ORACLE); } function setPriceOracle(address _priceOracle) public onlyOwner { _setAddress(PRICE_ORACLE, _priceOracle); emit PriceOracleUpdated(_priceOracle); } function getLendingRateOracle() public view returns (address) { return getAddress(LENDING_RATE_ORACLE); } function setLendingRateOracle(address _lendingRateOracle) public onlyOwner { _setAddress(LENDING_RATE_ORACLE, _lendingRateOracle); emit LendingRateOracleUpdated(_lendingRateOracle); } function getTokenDistributor() public view returns (address) { return getAddress(TOKEN_DISTRIBUTOR); } function setTokenDistributor(address _tokenDistributor) public onlyOwner { _setAddress(TOKEN_DISTRIBUTOR, _tokenDistributor); emit TokenDistributorUpdated(_tokenDistributor); } /** * @dev internal function to update the implementation of a specific component of the protocol * @param _id the id of the contract to be updated * @param _newAddress the address of the new implementation **/ function updateImplInternal(bytes32 _id, address _newAddress) internal { address payable proxyAddress = address(uint160(getAddress(_id))); InitializableAdminUpgradeabilityProxy proxy = InitializableAdminUpgradeabilityProxy(proxyAddress); bytes memory params = abi.encodeWithSignature("initialize(address)", address(this)); if (proxyAddress == address(0)) { proxy = new InitializableAdminUpgradeabilityProxy(); proxy.initialize(_newAddress, address(this), params); _setAddress(_id, address(proxy)); emit ProxyCreated(_id, address(proxy)); } else { proxy.upgradeToAndCall(_newAddress, params); } } } contract UintStorage { mapping(bytes32 => uint256) private uints; function getUint(bytes32 _key) public view returns (uint256) { return uints[_key]; } function _setUint(bytes32 _key, uint256 _value) internal { uints[_key] = _value; } } /** * @title LendingPoolParametersProvider * @author Aave * @notice stores the configuration parameters of the Lending Pool contract **/ contract LendingPoolParametersProvider is VersionedInitializable { uint256 private constant MAX_STABLE_RATE_BORROW_SIZE_PERCENT = 25; uint256 private constant REBALANCE_DOWN_RATE_DELTA = (1e27)/5; uint256 private constant FLASHLOAN_FEE_TOTAL = 35; uint256 private constant FLASHLOAN_FEE_PROTOCOL = 3000; uint256 constant private DATA_PROVIDER_REVISION = 0x1; function getRevision() internal pure returns(uint256) { return DATA_PROVIDER_REVISION; } /** * @dev initializes the LendingPoolParametersProvider after it's added to the proxy * @param _addressesProvider the address of the LendingPoolAddressesProvider */ function initialize(address _addressesProvider) public initializer { } /** * @dev returns the maximum stable rate borrow size, in percentage of the available liquidity. **/ function getMaxStableRateBorrowSizePercent() external pure returns (uint256) { return MAX_STABLE_RATE_BORROW_SIZE_PERCENT; } /** * @dev returns the delta between the current stable rate and the user stable rate at * which the borrow position of the user will be rebalanced (scaled down) **/ function getRebalanceDownRateDelta() external pure returns (uint256) { return REBALANCE_DOWN_RATE_DELTA; } /** * @dev returns the fee applied to a flashloan and the portion to redirect to the protocol, in basis points. **/ function getFlashLoanFeesInBips() external pure returns (uint256, uint256) { return (FLASHLOAN_FEE_TOTAL, FLASHLOAN_FEE_PROTOCOL); } } /** * @title CoreLibrary library * @author Aave * @notice Defines the data structures of the reserves and the user data **/ library CoreLibrary { using SafeMath for uint256; using WadRayMath for uint256; enum InterestRateMode {NONE, STABLE, VARIABLE} uint256 internal constant SECONDS_PER_YEAR = 365 days; struct UserReserveData { //principal amount borrowed by the user. uint256 principalBorrowBalance; //cumulated variable borrow index for the user. Expressed in ray uint256 lastVariableBorrowCumulativeIndex; //origination fee cumulated by the user uint256 originationFee; // stable borrow rate at which the user has borrowed. Expressed in ray uint256 stableBorrowRate; uint40 lastUpdateTimestamp; //defines if a specific deposit should or not be used as a collateral in borrows bool useAsCollateral; } struct ReserveData { /** * @dev refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. **/ //the liquidity index. Expressed in ray uint256 lastLiquidityCumulativeIndex; //the current supply rate. Expressed in ray uint256 currentLiquidityRate; //the total borrows of the reserve at a stable rate. Expressed in the currency decimals uint256 totalBorrowsStable; //the total borrows of the reserve at a variable rate. Expressed in the currency decimals uint256 totalBorrowsVariable; //the current variable borrow rate. Expressed in ray uint256 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint256 currentStableBorrowRate; //the current average stable borrow rate (weighted average of all the different stable rate loans). Expressed in ray uint256 currentAverageStableBorrowRate; //variable borrow index. Expressed in ray uint256 lastVariableBorrowCumulativeIndex; //the ltv of the reserve. Expressed in percentage (0-100) uint256 baseLTVasCollateral; //the liquidation threshold of the reserve. Expressed in percentage (0-100) uint256 liquidationThreshold; //the liquidation bonus of the reserve. Expressed in percentage uint256 liquidationBonus; //the decimals of the reserve asset uint256 decimals; /** * @dev address of the aToken representing the asset **/ address aTokenAddress; /** * @dev address of the interest rate strategy contract **/ address interestRateStrategyAddress; uint40 lastUpdateTimestamp; // borrowingEnabled = true means users can borrow from this reserve bool borrowingEnabled; // usageAsCollateralEnabled = true means users can use this reserve as collateral bool usageAsCollateralEnabled; // isStableBorrowRateEnabled = true means users can borrow at a stable rate bool isStableBorrowRateEnabled; // isActive = true means the reserve has been activated and properly configured bool isActive; // isFreezed = true means the reserve only allows repays and redeems, but not deposits, new borrowings or rate swap bool isFreezed; } /** * @dev returns the ongoing normalized income for the reserve. * a value of 1e27 means there is no income. As time passes, the income is accrued. * A value of 2*1e27 means that the income of the reserve is double the initial amount. * @param _reserve the reserve object * @return the normalized income. expressed in ray **/ function getNormalizedIncome(CoreLibrary.ReserveData storage _reserve) internal view returns (uint256) { uint256 cumulated = calculateLinearInterest( _reserve .currentLiquidityRate, _reserve .lastUpdateTimestamp ) .rayMul(_reserve.lastLiquidityCumulativeIndex); return cumulated; } /** * @dev Updates the liquidity cumulative index Ci and variable borrow cumulative index Bvc. Refer to the whitepaper for * a formal specification. * @param _self the reserve object **/ function updateCumulativeIndexes(ReserveData storage _self) internal { uint256 totalBorrows = getTotalBorrows(_self); if (totalBorrows > 0) { //only cumulating if there is any income being produced uint256 cumulatedLiquidityInterest = calculateLinearInterest( _self.currentLiquidityRate, _self.lastUpdateTimestamp ); _self.lastLiquidityCumulativeIndex = cumulatedLiquidityInterest.rayMul( _self.lastLiquidityCumulativeIndex ); uint256 cumulatedVariableBorrowInterest = calculateCompoundedInterest( _self.currentVariableBorrowRate, _self.lastUpdateTimestamp ); _self.lastVariableBorrowCumulativeIndex = cumulatedVariableBorrowInterest.rayMul( _self.lastVariableBorrowCumulativeIndex ); } } /** * @dev accumulates a predefined amount of asset to the reserve as a fixed, one time income. Used for example to accumulate * the flashloan fee to the reserve, and spread it through the depositors. * @param _self the reserve object * @param _totalLiquidity the total liquidity available in the reserve * @param _amount the amount to accomulate **/ function cumulateToLiquidityIndex( ReserveData storage _self, uint256 _totalLiquidity, uint256 _amount ) internal { uint256 amountToLiquidityRatio = _amount.wadToRay().rayDiv(_totalLiquidity.wadToRay()); uint256 cumulatedLiquidity = amountToLiquidityRatio.add(WadRayMath.ray()); _self.lastLiquidityCumulativeIndex = cumulatedLiquidity.rayMul( _self.lastLiquidityCumulativeIndex ); } /** * @dev initializes a reserve * @param _self the reserve object * @param _aTokenAddress the address of the overlying atoken contract * @param _decimals the number of decimals of the underlying asset * @param _interestRateStrategyAddress the address of the interest rate strategy contract **/ function init( ReserveData storage _self, address _aTokenAddress, uint256 _decimals, address _interestRateStrategyAddress ) external { require(_self.aTokenAddress == address(0), "Reserve has already been initialized"); if (_self.lastLiquidityCumulativeIndex == 0) { //if the reserve has not been initialized yet _self.lastLiquidityCumulativeIndex = WadRayMath.ray(); } if (_self.lastVariableBorrowCumulativeIndex == 0) { _self.lastVariableBorrowCumulativeIndex = WadRayMath.ray(); } _self.aTokenAddress = _aTokenAddress; _self.decimals = _decimals; _self.interestRateStrategyAddress = _interestRateStrategyAddress; _self.isActive = true; _self.isFreezed = false; } /** * @dev enables borrowing on a reserve * @param _self the reserve object * @param _stableBorrowRateEnabled true if the stable borrow rate must be enabled by default, false otherwise **/ function enableBorrowing(ReserveData storage _self, bool _stableBorrowRateEnabled) external { require(_self.borrowingEnabled == false, "Reserve is already enabled"); _self.borrowingEnabled = true; _self.isStableBorrowRateEnabled = _stableBorrowRateEnabled; } /** * @dev disables borrowing on a reserve * @param _self the reserve object **/ function disableBorrowing(ReserveData storage _self) external { _self.borrowingEnabled = false; } /** * @dev enables a reserve to be used as collateral * @param _self the reserve object * @param _baseLTVasCollateral the loan to value of the asset when used as collateral * @param _liquidationThreshold the threshold at which loans using this asset as collateral will be considered undercollateralized * @param _liquidationBonus the bonus liquidators receive to liquidate this asset **/ function enableAsCollateral( ReserveData storage _self, uint256 _baseLTVasCollateral, uint256 _liquidationThreshold, uint256 _liquidationBonus ) external { require( _self.usageAsCollateralEnabled == false, "Reserve is already enabled as collateral" ); _self.usageAsCollateralEnabled = true; _self.baseLTVasCollateral = _baseLTVasCollateral; _self.liquidationThreshold = _liquidationThreshold; _self.liquidationBonus = _liquidationBonus; if (_self.lastLiquidityCumulativeIndex == 0) _self.lastLiquidityCumulativeIndex = WadRayMath.ray(); } /** * @dev disables a reserve as collateral * @param _self the reserve object **/ function disableAsCollateral(ReserveData storage _self) external { _self.usageAsCollateralEnabled = false; } /** * @dev calculates the compounded borrow balance of a user * @param _self the userReserve object * @param _reserve the reserve object * @return the user compounded borrow balance **/ function getCompoundedBorrowBalance( CoreLibrary.UserReserveData storage _self, CoreLibrary.ReserveData storage _reserve ) internal view returns (uint256) { if (_self.principalBorrowBalance == 0) return 0; uint256 principalBorrowBalanceRay = _self.principalBorrowBalance.wadToRay(); uint256 compoundedBalance = 0; uint256 cumulatedInterest = 0; if (_self.stableBorrowRate > 0) { cumulatedInterest = calculateCompoundedInterest( _self.stableBorrowRate, _self.lastUpdateTimestamp ); } else { //variable interest cumulatedInterest = calculateCompoundedInterest( _reserve .currentVariableBorrowRate, _reserve .lastUpdateTimestamp ) .rayMul(_reserve.lastVariableBorrowCumulativeIndex) .rayDiv(_self.lastVariableBorrowCumulativeIndex); } compoundedBalance = principalBorrowBalanceRay.rayMul(cumulatedInterest).rayToWad(); if (compoundedBalance == _self.principalBorrowBalance) { //solium-disable-next-line if (_self.lastUpdateTimestamp != block.timestamp) { //no interest cumulation because of the rounding - we add 1 wei //as symbolic cumulated interest to avoid interest free loans. return _self.principalBorrowBalance.add(1 wei); } } return compoundedBalance; } /** * @dev increases the total borrows at a stable rate on a specific reserve and updates the * average stable rate consequently * @param _reserve the reserve object * @param _amount the amount to add to the total borrows stable * @param _rate the rate at which the amount has been borrowed **/ function increaseTotalBorrowsStableAndUpdateAverageRate( ReserveData storage _reserve, uint256 _amount, uint256 _rate ) internal { if(_amount == 0) { return; } uint256 previousTotalBorrowStable = _reserve.totalBorrowsStable; //updating reserve borrows stable _reserve.totalBorrowsStable = _reserve.totalBorrowsStable.add(_amount); //update the average stable rate //weighted average of all the borrows uint256 weightedLastBorrow = _amount.wadToRay().rayMul(_rate); uint256 weightedPreviousTotalBorrows = previousTotalBorrowStable.wadToRay().rayMul( _reserve.currentAverageStableBorrowRate ); _reserve.currentAverageStableBorrowRate = weightedLastBorrow .add(weightedPreviousTotalBorrows) .rayDiv(_reserve.totalBorrowsStable.wadToRay()); } /** * @dev decreases the total borrows at a stable rate on a specific reserve and updates the * average stable rate consequently * @param _reserve the reserve object * @param _amount the amount to substract to the total borrows stable * @param _rate the rate at which the amount has been repaid **/ function decreaseTotalBorrowsStableAndUpdateAverageRate( ReserveData storage _reserve, uint256 _amount, uint256 _rate ) internal { uint256 previousTotalBorrowStable = _reserve.totalBorrowsStable; if (previousTotalBorrowStable == 0 || _amount >= previousTotalBorrowStable) { _reserve.totalBorrowsStable = 0; _reserve.currentAverageStableBorrowRate = 0; // no income if there are no stable rate borrows return; } //updating reserve borrows stable _reserve.totalBorrowsStable = _reserve.totalBorrowsStable.sub(_amount); //update the average stable rate //weighted average of all the borrows uint256 weightedLastBorrow = _amount.wadToRay().rayMul(_rate); uint256 weightedPreviousTotalBorrows = previousTotalBorrowStable.wadToRay().rayMul( _reserve.currentAverageStableBorrowRate ); if( weightedPreviousTotalBorrows <= weightedLastBorrow ) { _reserve.totalBorrowsStable = 0; _reserve.currentAverageStableBorrowRate = 0; // no income if there are no stable rate borrows return; } _reserve.currentAverageStableBorrowRate = weightedPreviousTotalBorrows .sub(weightedLastBorrow) .rayDiv(_reserve.totalBorrowsStable.wadToRay()); } /** * @dev increases the total borrows at a variable rate * @param _reserve the reserve object * @param _amount the amount to add to the total borrows variable **/ function increaseTotalBorrowsVariable(ReserveData storage _reserve, uint256 _amount) internal { _reserve.totalBorrowsVariable = _reserve.totalBorrowsVariable.add(_amount); } /** * @dev decreases the total borrows at a variable rate * @param _reserve the reserve object * @param _amount the amount to substract to the total borrows variable **/ function decreaseTotalBorrowsVariable(ReserveData storage _reserve, uint256 _amount) internal { require( _reserve.totalBorrowsVariable >= _amount, "The amount that is being subtracted from the variable total borrows is incorrect" ); _reserve.totalBorrowsVariable = _reserve.totalBorrowsVariable.sub(_amount); } /** * @dev function to calculate the interest using a linear interest rate formula * @param _rate the interest rate, in ray * @param _lastUpdateTimestamp the timestamp of the last update of the interest * @return the interest rate linearly accumulated during the timeDelta, in ray **/ function calculateLinearInterest(uint256 _rate, uint40 _lastUpdateTimestamp) internal view returns (uint256) { //solium-disable-next-line uint256 timeDifference = block.timestamp.sub(uint256(_lastUpdateTimestamp)); uint256 timeDelta = timeDifference.wadToRay().rayDiv(SECONDS_PER_YEAR.wadToRay()); return _rate.rayMul(timeDelta).add(WadRayMath.ray()); } /** * @dev function to calculate the interest using a compounded interest rate formula * @param _rate the interest rate, in ray * @param _lastUpdateTimestamp the timestamp of the last update of the interest * @return the interest rate compounded during the timeDelta, in ray **/ function calculateCompoundedInterest(uint256 _rate, uint40 _lastUpdateTimestamp) internal view returns (uint256) { //solium-disable-next-line uint256 timeDifference = block.timestamp.sub(uint256(_lastUpdateTimestamp)); uint256 ratePerSecond = _rate.div(SECONDS_PER_YEAR); return ratePerSecond.add(WadRayMath.ray()).rayPow(timeDifference); } /** * @dev returns the total borrows on the reserve * @param _reserve the reserve object * @return the total borrows (stable + variable) **/ function getTotalBorrows(CoreLibrary.ReserveData storage _reserve) internal view returns (uint256) { return _reserve.totalBorrowsStable.add(_reserve.totalBorrowsVariable); } } /** * @title IPriceOracleGetter interface * @notice Interface for the Aave price oracle. **/ interface IPriceOracleGetter { /** * @dev returns the asset price in ETH * @param _asset the address of the asset * @return the ETH price of the asset **/ function getAssetPrice(address _asset) external view returns (uint256); } /** * @title IFeeProvider interface * @notice Interface for the Aave fee provider. **/ interface IFeeProvider { function calculateLoanOriginationFee(address _user, uint256 _amount) external view returns (uint256); function getLoanOriginationFeePercentage() external view returns (uint256); } /** * @title LendingPoolDataProvider contract * @author Aave * @notice Implements functions to fetch data from the core, and aggregate them in order to allow computation * on the compounded balances and the account balances in ETH **/ contract LendingPoolDataProvider is VersionedInitializable { using SafeMath for uint256; using WadRayMath for uint256; LendingPoolCore public core; LendingPoolAddressesProvider public addressesProvider; /** * @dev specifies the health factor threshold at which the user position is liquidated. * 1e18 by default, if the health factor drops below 1e18, the loan can be liquidated. **/ uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; uint256 public constant DATA_PROVIDER_REVISION = 0x1; function getRevision() internal pure returns (uint256) { return DATA_PROVIDER_REVISION; } function initialize(LendingPoolAddressesProvider _addressesProvider) public initializer { addressesProvider = _addressesProvider; core = LendingPoolCore(_addressesProvider.getLendingPoolCore()); } /** * @dev struct to hold calculateUserGlobalData() local computations **/ struct UserGlobalDataLocalVars { uint256 reserveUnitPrice; uint256 tokenUnit; uint256 compoundedLiquidityBalance; uint256 compoundedBorrowBalance; uint256 reserveDecimals; uint256 baseLtv; uint256 liquidationThreshold; uint256 originationFee; bool usageAsCollateralEnabled; bool userUsesReserveAsCollateral; address currentReserve; } /** * @dev calculates the user data across the reserves. * this includes the total liquidity/collateral/borrow balances in ETH, * the average Loan To Value, the average Liquidation Ratio, and the Health factor. * @param _user the address of the user * @return the total liquidity, total collateral, total borrow balances of the user in ETH. * also the average Ltv, liquidation threshold, and the health factor **/ function calculateUserGlobalData(address _user) public view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ) { IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle()); // Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables UserGlobalDataLocalVars memory vars; address[] memory reserves = core.getReserves(); for (uint256 i = 0; i < reserves.length; i++) { vars.currentReserve = reserves[i]; ( vars.compoundedLiquidityBalance, vars.compoundedBorrowBalance, vars.originationFee, vars.userUsesReserveAsCollateral ) = core.getUserBasicReserveData(vars.currentReserve, _user); if (vars.compoundedLiquidityBalance == 0 && vars.compoundedBorrowBalance == 0) { continue; } //fetch reserve data ( vars.reserveDecimals, vars.baseLtv, vars.liquidationThreshold, vars.usageAsCollateralEnabled ) = core.getReserveConfiguration(vars.currentReserve); vars.tokenUnit = 10 ** vars.reserveDecimals; vars.reserveUnitPrice = oracle.getAssetPrice(vars.currentReserve); //liquidity and collateral balance if (vars.compoundedLiquidityBalance > 0) { uint256 liquidityBalanceETH = vars .reserveUnitPrice .mul(vars.compoundedLiquidityBalance) .div(vars.tokenUnit); totalLiquidityBalanceETH = totalLiquidityBalanceETH.add(liquidityBalanceETH); if (vars.usageAsCollateralEnabled && vars.userUsesReserveAsCollateral) { totalCollateralBalanceETH = totalCollateralBalanceETH.add(liquidityBalanceETH); currentLtv = currentLtv.add(liquidityBalanceETH.mul(vars.baseLtv)); currentLiquidationThreshold = currentLiquidationThreshold.add( liquidityBalanceETH.mul(vars.liquidationThreshold) ); } } if (vars.compoundedBorrowBalance > 0) { totalBorrowBalanceETH = totalBorrowBalanceETH.add( vars.reserveUnitPrice.mul(vars.compoundedBorrowBalance).div(vars.tokenUnit) ); totalFeesETH = totalFeesETH.add( vars.originationFee.mul(vars.reserveUnitPrice).div(vars.tokenUnit) ); } } currentLtv = totalCollateralBalanceETH > 0 ? currentLtv.div(totalCollateralBalanceETH) : 0; currentLiquidationThreshold = totalCollateralBalanceETH > 0 ? currentLiquidationThreshold.div(totalCollateralBalanceETH) : 0; healthFactor = calculateHealthFactorFromBalancesInternal( totalCollateralBalanceETH, totalBorrowBalanceETH, totalFeesETH, currentLiquidationThreshold ); healthFactorBelowThreshold = healthFactor < HEALTH_FACTOR_LIQUIDATION_THRESHOLD; } struct balanceDecreaseAllowedLocalVars { uint256 decimals; uint256 collateralBalanceETH; uint256 borrowBalanceETH; uint256 totalFeesETH; uint256 currentLiquidationThreshold; uint256 reserveLiquidationThreshold; uint256 amountToDecreaseETH; uint256 collateralBalancefterDecrease; uint256 liquidationThresholdAfterDecrease; uint256 healthFactorAfterDecrease; bool reserveUsageAsCollateralEnabled; } /** * @dev check if a specific balance decrease is allowed (i.e. doesn't bring the user borrow position health factor under 1e18) * @param _reserve the address of the reserve * @param _user the address of the user * @param _amount the amount to decrease * @return true if the decrease of the balance is allowed **/ function balanceDecreaseAllowed(address _reserve, address _user, uint256 _amount) external view returns (bool) { // Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables balanceDecreaseAllowedLocalVars memory vars; ( vars.decimals, , vars.reserveLiquidationThreshold, vars.reserveUsageAsCollateralEnabled ) = core.getReserveConfiguration(_reserve); if ( !vars.reserveUsageAsCollateralEnabled || !core.isUserUseReserveAsCollateralEnabled(_reserve, _user) ) { return true; //if reserve is not used as collateral, no reasons to block the transfer } ( , vars.collateralBalanceETH, vars.borrowBalanceETH, vars.totalFeesETH, , vars.currentLiquidationThreshold, , ) = calculateUserGlobalData(_user); if (vars.borrowBalanceETH == 0) { return true; //no borrows - no reasons to block the transfer } IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle()); vars.amountToDecreaseETH = oracle.getAssetPrice(_reserve).mul(_amount).div( 10 ** vars.decimals ); vars.collateralBalancefterDecrease = vars.collateralBalanceETH.sub( vars.amountToDecreaseETH ); //if there is a borrow, there can't be 0 collateral if (vars.collateralBalancefterDecrease == 0) { return false; } vars.liquidationThresholdAfterDecrease = vars .collateralBalanceETH .mul(vars.currentLiquidationThreshold) .sub(vars.amountToDecreaseETH.mul(vars.reserveLiquidationThreshold)) .div(vars.collateralBalancefterDecrease); uint256 healthFactorAfterDecrease = calculateHealthFactorFromBalancesInternal( vars.collateralBalancefterDecrease, vars.borrowBalanceETH, vars.totalFeesETH, vars.liquidationThresholdAfterDecrease ); return healthFactorAfterDecrease > HEALTH_FACTOR_LIQUIDATION_THRESHOLD; } /** * @notice calculates the amount of collateral needed in ETH to cover a new borrow. * @param _reserve the reserve from which the user wants to borrow * @param _amount the amount the user wants to borrow * @param _fee the fee for the amount that the user needs to cover * @param _userCurrentBorrowBalanceTH the current borrow balance of the user (before the borrow) * @param _userCurrentLtv the average ltv of the user given his current collateral * @return the total amount of collateral in ETH to cover the current borrow balance + the new amount + fee **/ function calculateCollateralNeededInETH( address _reserve, uint256 _amount, uint256 _fee, uint256 _userCurrentBorrowBalanceTH, uint256 _userCurrentFeesETH, uint256 _userCurrentLtv ) external view returns (uint256) { uint256 reserveDecimals = core.getReserveDecimals(_reserve); IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle()); uint256 requestedBorrowAmountETH = oracle .getAssetPrice(_reserve) .mul(_amount.add(_fee)) .div(10 ** reserveDecimals); //price is in ether //add the current already borrowed amount to the amount requested to calculate the total collateral needed. uint256 collateralNeededInETH = _userCurrentBorrowBalanceTH .add(_userCurrentFeesETH) .add(requestedBorrowAmountETH) .mul(100) .div(_userCurrentLtv); //LTV is calculated in percentage return collateralNeededInETH; } /** * @dev calculates the equivalent amount in ETH that an user can borrow, depending on the available collateral and the * average Loan To Value. * @param collateralBalanceETH the total collateral balance * @param borrowBalanceETH the total borrow balance * @param totalFeesETH the total fees * @param ltv the average loan to value * @return the amount available to borrow in ETH for the user **/ function calculateAvailableBorrowsETHInternal( uint256 collateralBalanceETH, uint256 borrowBalanceETH, uint256 totalFeesETH, uint256 ltv ) internal view returns (uint256) { uint256 availableBorrowsETH = collateralBalanceETH.mul(ltv).div(100); //ltv is in percentage if (availableBorrowsETH < borrowBalanceETH) { return 0; } availableBorrowsETH = availableBorrowsETH.sub(borrowBalanceETH.add(totalFeesETH)); //calculate fee uint256 borrowFee = IFeeProvider(addressesProvider.getFeeProvider()) .calculateLoanOriginationFee(msg.sender, availableBorrowsETH); return availableBorrowsETH.sub(borrowFee); } /** * @dev calculates the health factor from the corresponding balances * @param collateralBalanceETH the total collateral balance in ETH * @param borrowBalanceETH the total borrow balance in ETH * @param totalFeesETH the total fees in ETH * @param liquidationThreshold the avg liquidation threshold **/ function calculateHealthFactorFromBalancesInternal( uint256 collateralBalanceETH, uint256 borrowBalanceETH, uint256 totalFeesETH, uint256 liquidationThreshold ) internal pure returns (uint256) { if (borrowBalanceETH == 0) return uint256(-1); return (collateralBalanceETH.mul(liquidationThreshold).div(100)).wadDiv( borrowBalanceETH.add(totalFeesETH) ); } /** * @dev returns the health factor liquidation threshold **/ function getHealthFactorLiquidationThreshold() public pure returns (uint256) { return HEALTH_FACTOR_LIQUIDATION_THRESHOLD; } /** * @dev accessory functions to fetch data from the lendingPoolCore **/ function getReserveConfigurationData(address _reserve) external view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ) { (, ltv, liquidationThreshold, usageAsCollateralEnabled) = core.getReserveConfiguration( _reserve ); stableBorrowRateEnabled = core.getReserveIsStableBorrowRateEnabled(_reserve); borrowingEnabled = core.isReserveBorrowingEnabled(_reserve); isActive = core.getReserveIsActive(_reserve); liquidationBonus = core.getReserveLiquidationBonus(_reserve); rateStrategyAddress = core.getReserveInterestRateStrategyAddress(_reserve); } function getReserveData(address _reserve) external view returns ( uint256 totalLiquidity, uint256 availableLiquidity, uint256 totalBorrowsStable, uint256 totalBorrowsVariable, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 utilizationRate, uint256 liquidityIndex, uint256 variableBorrowIndex, address aTokenAddress, uint40 lastUpdateTimestamp ) { totalLiquidity = core.getReserveTotalLiquidity(_reserve); availableLiquidity = core.getReserveAvailableLiquidity(_reserve); totalBorrowsStable = core.getReserveTotalBorrowsStable(_reserve); totalBorrowsVariable = core.getReserveTotalBorrowsVariable(_reserve); liquidityRate = core.getReserveCurrentLiquidityRate(_reserve); variableBorrowRate = core.getReserveCurrentVariableBorrowRate(_reserve); stableBorrowRate = core.getReserveCurrentStableBorrowRate(_reserve); averageStableBorrowRate = core.getReserveCurrentAverageStableBorrowRate(_reserve); utilizationRate = core.getReserveUtilizationRate(_reserve); liquidityIndex = core.getReserveLiquidityCumulativeIndex(_reserve); variableBorrowIndex = core.getReserveVariableBorrowsCumulativeIndex(_reserve); aTokenAddress = core.getReserveATokenAddress(_reserve); lastUpdateTimestamp = core.getReserveLastUpdate(_reserve); } function getUserAccountData(address _user) external view returns ( uint256 totalLiquidityETH, uint256 totalCollateralETH, uint256 totalBorrowsETH, uint256 totalFeesETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) { ( totalLiquidityETH, totalCollateralETH, totalBorrowsETH, totalFeesETH, ltv, currentLiquidationThreshold, healthFactor, ) = calculateUserGlobalData(_user); availableBorrowsETH = calculateAvailableBorrowsETHInternal( totalCollateralETH, totalBorrowsETH, totalFeesETH, ltv ); } function getUserReserveData(address _reserve, address _user) external view returns ( uint256 currentATokenBalance, uint256 currentBorrowBalance, uint256 principalBorrowBalance, uint256 borrowRateMode, uint256 borrowRate, uint256 liquidityRate, uint256 originationFee, uint256 variableBorrowIndex, uint256 lastUpdateTimestamp, bool usageAsCollateralEnabled ) { currentATokenBalance = AToken(core.getReserveATokenAddress(_reserve)).balanceOf(_user); CoreLibrary.InterestRateMode mode = core.getUserCurrentBorrowRateMode(_reserve, _user); (principalBorrowBalance, currentBorrowBalance, ) = core.getUserBorrowBalances( _reserve, _user ); //default is 0, if mode == CoreLibrary.InterestRateMode.NONE if (mode == CoreLibrary.InterestRateMode.STABLE) { borrowRate = core.getUserCurrentStableBorrowRate(_reserve, _user); } else if (mode == CoreLibrary.InterestRateMode.VARIABLE) { borrowRate = core.getReserveCurrentVariableBorrowRate(_reserve); } borrowRateMode = uint256(mode); liquidityRate = core.getReserveCurrentLiquidityRate(_reserve); originationFee = core.getUserOriginationFee(_reserve, _user); variableBorrowIndex = core.getUserVariableBorrowCumulativeIndex(_reserve, _user); lastUpdateTimestamp = core.getUserLastUpdate(_reserve, _user); usageAsCollateralEnabled = core.isUserUseReserveAsCollateralEnabled(_reserve, _user); } } /** * @title Aave ERC20 AToken * * @dev Implementation of the interest bearing token for the DLP protocol. * @author Aave */ contract AToken is ERC20, ERC20Detailed { using WadRayMath for uint256; uint256 public constant UINT_MAX_VALUE = uint256(-1); /** * @dev emitted after the redeem action * @param _from the address performing the redeem * @param _value the amount to be redeemed * @param _fromBalanceIncrease the cumulated balance since the last update of the user * @param _fromIndex the last index of the user **/ event Redeem( address indexed _from, uint256 _value, uint256 _fromBalanceIncrease, uint256 _fromIndex ); /** * @dev emitted after the mint action * @param _from the address performing the mint * @param _value the amount to be minted * @param _fromBalanceIncrease the cumulated balance since the last update of the user * @param _fromIndex the last index of the user **/ event MintOnDeposit( address indexed _from, uint256 _value, uint256 _fromBalanceIncrease, uint256 _fromIndex ); /** * @dev emitted during the liquidation action, when the liquidator reclaims the underlying * asset * @param _from the address from which the tokens are being burned * @param _value the amount to be burned * @param _fromBalanceIncrease the cumulated balance since the last update of the user * @param _fromIndex the last index of the user **/ event BurnOnLiquidation( address indexed _from, uint256 _value, uint256 _fromBalanceIncrease, uint256 _fromIndex ); /** * @dev emitted during the transfer action * @param _from the address from which the tokens are being transferred * @param _to the adress of the destination * @param _value the amount to be minted * @param _fromBalanceIncrease the cumulated balance since the last update of the user * @param _toBalanceIncrease the cumulated balance since the last update of the destination * @param _fromIndex the last index of the user * @param _toIndex the last index of the liquidator **/ event BalanceTransfer( address indexed _from, address indexed _to, uint256 _value, uint256 _fromBalanceIncrease, uint256 _toBalanceIncrease, uint256 _fromIndex, uint256 _toIndex ); /** * @dev emitted when the accumulation of the interest * by an user is redirected to another user * @param _from the address from which the interest is being redirected * @param _to the adress of the destination * @param _fromBalanceIncrease the cumulated balance since the last update of the user * @param _fromIndex the last index of the user **/ event InterestStreamRedirected( address indexed _from, address indexed _to, uint256 _redirectedBalance, uint256 _fromBalanceIncrease, uint256 _fromIndex ); /** * @dev emitted when the redirected balance of an user is being updated * @param _targetAddress the address of which the balance is being updated * @param _targetBalanceIncrease the cumulated balance since the last update of the target * @param _targetIndex the last index of the user * @param _redirectedBalanceAdded the redirected balance being added * @param _redirectedBalanceRemoved the redirected balance being removed **/ event RedirectedBalanceUpdated( address indexed _targetAddress, uint256 _targetBalanceIncrease, uint256 _targetIndex, uint256 _redirectedBalanceAdded, uint256 _redirectedBalanceRemoved ); event InterestRedirectionAllowanceChanged( address indexed _from, address indexed _to ); address public underlyingAssetAddress; mapping (address => uint256) private userIndexes; mapping (address => address) private interestRedirectionAddresses; mapping (address => uint256) private redirectedBalances; mapping (address => address) private interestRedirectionAllowances; LendingPoolAddressesProvider private addressesProvider; LendingPoolCore private core; LendingPool private pool; LendingPoolDataProvider private dataProvider; modifier onlyLendingPool { require( msg.sender == address(pool), "The caller of this function must be a lending pool" ); _; } modifier whenTransferAllowed(address _from, uint256 _amount) { require(isTransferAllowed(_from, _amount), "Transfer cannot be allowed."); _; } constructor( LendingPoolAddressesProvider _addressesProvider, address _underlyingAsset, uint8 _underlyingAssetDecimals, string memory _name, string memory _symbol ) public ERC20Detailed(_name, _symbol, _underlyingAssetDecimals) { addressesProvider = _addressesProvider; core = LendingPoolCore(addressesProvider.getLendingPoolCore()); pool = LendingPool(addressesProvider.getLendingPool()); dataProvider = LendingPoolDataProvider(addressesProvider.getLendingPoolDataProvider()); underlyingAssetAddress = _underlyingAsset; } /** * @notice ERC20 implementation internal function backing transfer() and transferFrom() * @dev validates the transfer before allowing it. NOTE: This is not standard ERC20 behavior **/ function _transfer(address _from, address _to, uint256 _amount) internal whenTransferAllowed(_from, _amount) { executeTransferInternal(_from, _to, _amount); } /** * @dev redirects the interest generated to a target address. * when the interest is redirected, the user balance is added to * the recepient redirected balance. * @param _to the address to which the interest will be redirected **/ function redirectInterestStream(address _to) external { redirectInterestStreamInternal(msg.sender, _to); } /** * @dev redirects the interest generated by _from to a target address. * when the interest is redirected, the user balance is added to * the recepient redirected balance. The caller needs to have allowance on * the interest redirection to be able to execute the function. * @param _from the address of the user whom interest is being redirected * @param _to the address to which the interest will be redirected **/ function redirectInterestStreamOf(address _from, address _to) external { require( msg.sender == interestRedirectionAllowances[_from], "Caller is not allowed to redirect the interest of the user" ); redirectInterestStreamInternal(_from,_to); } /** * @dev gives allowance to an address to execute the interest redirection * on behalf of the caller. * @param _to the address to which the interest will be redirected. Pass address(0) to reset * the allowance. **/ function allowInterestRedirectionTo(address _to) external { require(_to != msg.sender, "User cannot give allowance to himself"); interestRedirectionAllowances[msg.sender] = _to; emit InterestRedirectionAllowanceChanged( msg.sender, _to ); } /** * @dev redeems aToken for the underlying asset * @param _amount the amount being redeemed **/ function redeem(uint256 _amount) external { require(_amount > 0, "Amount to redeem needs to be > 0"); //cumulates the balance of the user (, uint256 currentBalance, uint256 balanceIncrease, uint256 index) = cumulateBalanceInternal(msg.sender); uint256 amountToRedeem = _amount; //if amount is equal to uint(-1), the user wants to redeem everything if(_amount == UINT_MAX_VALUE){ amountToRedeem = currentBalance; } require(amountToRedeem <= currentBalance, "User cannot redeem more than the available balance"); //check that the user is allowed to redeem the amount require(isTransferAllowed(msg.sender, amountToRedeem), "Transfer cannot be allowed."); //if the user is redirecting his interest towards someone else, //we update the redirected balance of the redirection address by adding the accrued interest, //and removing the amount to redeem updateRedirectedBalanceOfRedirectionAddressInternal(msg.sender, balanceIncrease, amountToRedeem); // burns tokens equivalent to the amount requested _burn(msg.sender, amountToRedeem); bool userIndexReset = false; //reset the user data if the remaining balance is 0 if(currentBalance.sub(amountToRedeem) == 0){ userIndexReset = resetDataOnZeroBalanceInternal(msg.sender); } // executes redeem of the underlying asset pool.redeemUnderlying( underlyingAssetAddress, msg.sender, amountToRedeem, currentBalance.sub(amountToRedeem) ); emit Redeem(msg.sender, amountToRedeem, balanceIncrease, userIndexReset ? 0 : index); } /** * @dev mints token in the event of users depositing the underlying asset into the lending pool * only lending pools can call this function * @param _account the address receiving the minted tokens * @param _amount the amount of tokens to mint */ function mintOnDeposit(address _account, uint256 _amount) external onlyLendingPool { //cumulates the balance of the user (, , uint256 balanceIncrease, uint256 index) = cumulateBalanceInternal(_account); //if the user is redirecting his interest towards someone else, //we update the redirected balance of the redirection address by adding the accrued interest //and the amount deposited updateRedirectedBalanceOfRedirectionAddressInternal(_account, balanceIncrease.add(_amount), 0); //mint an equivalent amount of tokens to cover the new deposit _mint(_account, _amount); emit MintOnDeposit(_account, _amount, balanceIncrease, index); } /** * @dev burns token in the event of a borrow being liquidated, in case the liquidators reclaims the underlying asset * Transfer of the liquidated asset is executed by the lending pool contract. * only lending pools can call this function * @param _account the address from which burn the aTokens * @param _value the amount to burn **/ function burnOnLiquidation(address _account, uint256 _value) external onlyLendingPool { //cumulates the balance of the user being liquidated (,uint256 accountBalance,uint256 balanceIncrease,uint256 index) = cumulateBalanceInternal(_account); //adds the accrued interest and substracts the burned amount to //the redirected balance updateRedirectedBalanceOfRedirectionAddressInternal(_account, balanceIncrease, _value); //burns the requested amount of tokens _burn(_account, _value); bool userIndexReset = false; //reset the user data if the remaining balance is 0 if(accountBalance.sub(_value) == 0){ userIndexReset = resetDataOnZeroBalanceInternal(_account); } emit BurnOnLiquidation(_account, _value, balanceIncrease, userIndexReset ? 0 : index); } /** * @dev transfers tokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * only lending pools can call this function * @param _from the address from which transfer the aTokens * @param _to the destination address * @param _value the amount to transfer **/ function transferOnLiquidation(address _from, address _to, uint256 _value) external onlyLendingPool { //being a normal transfer, the Transfer() and BalanceTransfer() are emitted //so no need to emit a specific event here executeTransferInternal(_from, _to, _value); } /** * @dev calculates the balance of the user, which is the * principal balance + interest generated by the principal balance + interest generated by the redirected balance * @param _user the user for which the balance is being calculated * @return the total balance of the user **/ function balanceOf(address _user) public view returns(uint256) { //current principal balance of the user uint256 currentPrincipalBalance = super.balanceOf(_user); //balance redirected by other users to _user for interest rate accrual uint256 redirectedBalance = redirectedBalances[_user]; if(currentPrincipalBalance == 0 && redirectedBalance == 0){ return 0; } //if the _user is not redirecting the interest to anybody, accrues //the interest for himself if(interestRedirectionAddresses[_user] == address(0)){ //accruing for himself means that both the principal balance and //the redirected balance partecipate in the interest return calculateCumulatedBalanceInternal( _user, currentPrincipalBalance.add(redirectedBalance) ) .sub(redirectedBalance); } else { //if the user redirected the interest, then only the redirected //balance generates interest. In that case, the interest generated //by the redirected balance is added to the current principal balance. return currentPrincipalBalance.add( calculateCumulatedBalanceInternal( _user, redirectedBalance ) .sub(redirectedBalance) ); } } /** * @dev returns the principal balance of the user. The principal balance is the last * updated stored balance, which does not consider the perpetually accruing interest. * @param _user the address of the user * @return the principal balance of the user **/ function principalBalanceOf(address _user) external view returns(uint256) { return super.balanceOf(_user); } /** * @dev calculates the total supply of the specific aToken * since the balance of every single user increases over time, the total supply * does that too. * @return the current total supply **/ function totalSupply() public view returns(uint256) { uint256 currentSupplyPrincipal = super.totalSupply(); if(currentSupplyPrincipal == 0){ return 0; } return currentSupplyPrincipal .wadToRay() .rayMul(core.getReserveNormalizedIncome(underlyingAssetAddress)) .rayToWad(); } /** * @dev Used to validate transfers before actually executing them. * @param _user address of the user to check * @param _amount the amount to check * @return true if the _user can transfer _amount, false otherwise **/ function isTransferAllowed(address _user, uint256 _amount) public view returns (bool) { return dataProvider.balanceDecreaseAllowed(underlyingAssetAddress, _user, _amount); } /** * @dev returns the last index of the user, used to calculate the balance of the user * @param _user address of the user * @return the last user index **/ function getUserIndex(address _user) external view returns(uint256) { return userIndexes[_user]; } /** * @dev returns the address to which the interest is redirected * @param _user address of the user * @return 0 if there is no redirection, an address otherwise **/ function getInterestRedirectionAddress(address _user) external view returns(address) { return interestRedirectionAddresses[_user]; } /** * @dev returns the redirected balance of the user. The redirected balance is the balance * redirected by other accounts to the user, that is accrueing interest for him. * @param _user address of the user * @return the total redirected balance **/ function getRedirectedBalance(address _user) external view returns(uint256) { return redirectedBalances[_user]; } /** * @dev accumulates the accrued interest of the user to the principal balance * @param _user the address of the user for which the interest is being accumulated * @return the previous principal balance, the new principal balance, the balance increase * and the new user index **/ function cumulateBalanceInternal(address _user) internal returns(uint256, uint256, uint256, uint256) { uint256 previousPrincipalBalance = super.balanceOf(_user); //calculate the accrued interest since the last accumulation uint256 balanceIncrease = balanceOf(_user).sub(previousPrincipalBalance); //mints an amount of tokens equivalent to the amount accumulated _mint(_user, balanceIncrease); //updates the user index uint256 index = userIndexes[_user] = core.getReserveNormalizedIncome(underlyingAssetAddress); return ( previousPrincipalBalance, previousPrincipalBalance.add(balanceIncrease), balanceIncrease, index ); } /** * @dev updates the redirected balance of the user. If the user is not redirecting his * interest, nothing is executed. * @param _user the address of the user for which the interest is being accumulated * @param _balanceToAdd the amount to add to the redirected balance * @param _balanceToRemove the amount to remove from the redirected balance **/ function updateRedirectedBalanceOfRedirectionAddressInternal( address _user, uint256 _balanceToAdd, uint256 _balanceToRemove ) internal { address redirectionAddress = interestRedirectionAddresses[_user]; //if there isn't any redirection, nothing to be done if(redirectionAddress == address(0)){ return; } //compound balances of the redirected address (,,uint256 balanceIncrease, uint256 index) = cumulateBalanceInternal(redirectionAddress); //updating the redirected balance redirectedBalances[redirectionAddress] = redirectedBalances[redirectionAddress] .add(_balanceToAdd) .sub(_balanceToRemove); //if the interest of redirectionAddress is also being redirected, we need to update //the redirected balance of the redirection target by adding the balance increase address targetOfRedirectionAddress = interestRedirectionAddresses[redirectionAddress]; if(targetOfRedirectionAddress != address(0)){ redirectedBalances[targetOfRedirectionAddress] = redirectedBalances[targetOfRedirectionAddress].add(balanceIncrease); } emit RedirectedBalanceUpdated( redirectionAddress, balanceIncrease, index, _balanceToAdd, _balanceToRemove ); } /** * @dev calculate the interest accrued by _user on a specific balance * @param _user the address of the user for which the interest is being accumulated * @param _balance the balance on which the interest is calculated * @return the interest rate accrued **/ function calculateCumulatedBalanceInternal( address _user, uint256 _balance ) internal view returns (uint256) { return _balance .wadToRay() .rayMul(core.getReserveNormalizedIncome(underlyingAssetAddress)) .rayDiv(userIndexes[_user]) .rayToWad(); } /** * @dev executes the transfer of aTokens, invoked by both _transfer() and * transferOnLiquidation() * @param _from the address from which transfer the aTokens * @param _to the destination address * @param _value the amount to transfer **/ function executeTransferInternal( address _from, address _to, uint256 _value ) internal { require(_value > 0, "Transferred amount needs to be greater than zero"); //cumulate the balance of the sender (, uint256 fromBalance, uint256 fromBalanceIncrease, uint256 fromIndex ) = cumulateBalanceInternal(_from); //cumulate the balance of the receiver (, , uint256 toBalanceIncrease, uint256 toIndex ) = cumulateBalanceInternal(_to); //if the sender is redirecting his interest towards someone else, //adds to the redirected balance the accrued interest and removes the amount //being transferred updateRedirectedBalanceOfRedirectionAddressInternal(_from, fromBalanceIncrease, _value); //if the receiver is redirecting his interest towards someone else, //adds to the redirected balance the accrued interest and the amount //being transferred updateRedirectedBalanceOfRedirectionAddressInternal(_to, toBalanceIncrease.add(_value), 0); //performs the transfer super._transfer(_from, _to, _value); bool fromIndexReset = false; //reset the user data if the remaining balance is 0 if(fromBalance.sub(_value) == 0){ fromIndexReset = resetDataOnZeroBalanceInternal(_from); } emit BalanceTransfer( _from, _to, _value, fromBalanceIncrease, toBalanceIncrease, fromIndexReset ? 0 : fromIndex, toIndex ); } /** * @dev executes the redirection of the interest from one address to another. * immediately after redirection, the destination address will start to accrue interest. * @param _from the address from which transfer the aTokens * @param _to the destination address **/ function redirectInterestStreamInternal( address _from, address _to ) internal { address currentRedirectionAddress = interestRedirectionAddresses[_from]; require(_to != currentRedirectionAddress, "Interest is already redirected to the user"); //accumulates the accrued interest to the principal (uint256 previousPrincipalBalance, uint256 fromBalance, uint256 balanceIncrease, uint256 fromIndex) = cumulateBalanceInternal(_from); require(fromBalance > 0, "Interest stream can only be redirected if there is a valid balance"); //if the user is already redirecting the interest to someone, before changing //the redirection address we substract the redirected balance of the previous //recipient if(currentRedirectionAddress != address(0)){ updateRedirectedBalanceOfRedirectionAddressInternal(_from,0, previousPrincipalBalance); } //if the user is redirecting the interest back to himself, //we simply set to 0 the interest redirection address if(_to == _from) { interestRedirectionAddresses[_from] = address(0); emit InterestStreamRedirected( _from, address(0), fromBalance, balanceIncrease, fromIndex ); return; } //first set the redirection address to the new recipient interestRedirectionAddresses[_from] = _to; //adds the user balance to the redirected balance of the destination updateRedirectedBalanceOfRedirectionAddressInternal(_from,fromBalance,0); emit InterestStreamRedirected( _from, _to, fromBalance, balanceIncrease, fromIndex ); } /** * @dev function to reset the interest stream redirection and the user index, if the * user has no balance left. * @param _user the address of the user * @return true if the user index has also been reset, false otherwise. useful to emit the proper user index value **/ function resetDataOnZeroBalanceInternal(address _user) internal returns(bool) { //if the user has 0 principal balance, the interest stream redirection gets reset interestRedirectionAddresses[_user] = address(0); //emits a InterestStreamRedirected event to notify that the redirection has been reset emit InterestStreamRedirected(_user, address(0),0,0,0); //if the redirected balance is also 0, we clear up the user index if(redirectedBalances[_user] == 0){ userIndexes[_user] = 0; return true; } else{ return false; } } } /** * @title IFlashLoanReceiver interface * @notice Interface for the Aave fee IFlashLoanReceiver. * @author Aave * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external; } /** * @title ILendingRateOracle interface * @notice Interface for the Aave borrow rate oracle. Provides the average market borrow rate to be used as a base for the stable borrow rate calculations **/ interface ILendingRateOracle { /** @dev returns the market borrow rate in ray **/ function getMarketBorrowRate(address _asset) external view returns (uint256); /** @dev sets the market borrow rate. Rate value must be in ray **/ function setMarketBorrowRate(address _asset, uint256 _rate) external; } /** @title IReserveInterestRateStrategyInterface interface @notice Interface for the calculation of the interest rates. */ interface IReserveInterestRateStrategy { /** * @dev returns the base variable borrow rate, in rays */ function getBaseVariableBorrowRate() external view returns (uint256); /** * @dev calculates the liquidity, stable, and variable rates depending on the current utilization rate * and the base parameters * */ function calculateInterestRates( address _reserve, uint256 _utilizationRate, uint256 _totalBorrowsStable, uint256 _totalBorrowsVariable, uint256 _averageStableBorrowRate) external view returns (uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate); } library EthAddressLib { /** * @dev returns the address used within the protocol to identify ETH * @return the address assigned to ETH */ function ethAddress() internal pure returns(address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } /** * @title LendingPool contract * @notice Implements the actions of the LendingPool, and exposes accessory methods to fetch the users and reserve data * @author Aave **/ contract LendingPool is ReentrancyGuard, VersionedInitializable { using SafeMath for uint256; using WadRayMath for uint256; using Address for address; LendingPoolAddressesProvider public addressesProvider; LendingPoolCore public core; LendingPoolDataProvider public dataProvider; LendingPoolParametersProvider public parametersProvider; IFeeProvider feeProvider; /** * @dev emitted on deposit * @param _reserve the address of the reserve * @param _user the address of the user * @param _amount the amount to be deposited * @param _referral the referral number of the action * @param _timestamp the timestamp of the action **/ event Deposit( address indexed _reserve, address indexed _user, uint256 _amount, uint16 indexed _referral, uint256 _timestamp ); /** * @dev emitted during a redeem action. * @param _reserve the address of the reserve * @param _user the address of the user * @param _amount the amount to be deposited * @param _timestamp the timestamp of the action **/ event RedeemUnderlying( address indexed _reserve, address indexed _user, uint256 _amount, uint256 _timestamp ); /** * @dev emitted on borrow * @param _reserve the address of the reserve * @param _user the address of the user * @param _amount the amount to be deposited * @param _borrowRateMode the rate mode, can be either 1-stable or 2-variable * @param _borrowRate the rate at which the user has borrowed * @param _originationFee the origination fee to be paid by the user * @param _borrowBalanceIncrease the balance increase since the last borrow, 0 if it's the first time borrowing * @param _referral the referral number of the action * @param _timestamp the timestamp of the action **/ event Borrow( address indexed _reserve, address indexed _user, uint256 _amount, uint256 _borrowRateMode, uint256 _borrowRate, uint256 _originationFee, uint256 _borrowBalanceIncrease, uint16 indexed _referral, uint256 _timestamp ); /** * @dev emitted on repay * @param _reserve the address of the reserve * @param _user the address of the user for which the repay has been executed * @param _repayer the address of the user that has performed the repay action * @param _amountMinusFees the amount repaid minus fees * @param _fees the fees repaid * @param _borrowBalanceIncrease the balance increase since the last action * @param _timestamp the timestamp of the action **/ event Repay( address indexed _reserve, address indexed _user, address indexed _repayer, uint256 _amountMinusFees, uint256 _fees, uint256 _borrowBalanceIncrease, uint256 _timestamp ); /** * @dev emitted when a user performs a rate swap * @param _reserve the address of the reserve * @param _user the address of the user executing the swap * @param _newRateMode the new interest rate mode * @param _newRate the new borrow rate * @param _borrowBalanceIncrease the balance increase since the last action * @param _timestamp the timestamp of the action **/ event Swap( address indexed _reserve, address indexed _user, uint256 _newRateMode, uint256 _newRate, uint256 _borrowBalanceIncrease, uint256 _timestamp ); /** * @dev emitted when a user enables a reserve as collateral * @param _reserve the address of the reserve * @param _user the address of the user **/ event ReserveUsedAsCollateralEnabled(address indexed _reserve, address indexed _user); /** * @dev emitted when a user disables a reserve as collateral * @param _reserve the address of the reserve * @param _user the address of the user **/ event ReserveUsedAsCollateralDisabled(address indexed _reserve, address indexed _user); /** * @dev emitted when the stable rate of a user gets rebalanced * @param _reserve the address of the reserve * @param _user the address of the user for which the rebalance has been executed * @param _newStableRate the new stable borrow rate after the rebalance * @param _borrowBalanceIncrease the balance increase since the last action * @param _timestamp the timestamp of the action **/ event RebalanceStableBorrowRate( address indexed _reserve, address indexed _user, uint256 _newStableRate, uint256 _borrowBalanceIncrease, uint256 _timestamp ); /** * @dev emitted when a flashloan is executed * @param _target the address of the flashLoanReceiver * @param _reserve the address of the reserve * @param _amount the amount requested * @param _totalFee the total fee on the amount * @param _protocolFee the part of the fee for the protocol * @param _timestamp the timestamp of the action **/ event FlashLoan( address indexed _target, address indexed _reserve, uint256 _amount, uint256 _totalFee, uint256 _protocolFee, uint256 _timestamp ); /** * @dev these events are not emitted directly by the LendingPool * but they are declared here as the LendingPoolLiquidationManager * is executed using a delegateCall(). * This allows to have the events in the generated ABI for LendingPool. **/ /** * @dev emitted when a borrow fee is liquidated * @param _collateral the address of the collateral being liquidated * @param _reserve the address of the reserve * @param _user the address of the user being liquidated * @param _feeLiquidated the total fee liquidated * @param _liquidatedCollateralForFee the amount of collateral received by the protocol in exchange for the fee * @param _timestamp the timestamp of the action **/ event OriginationFeeLiquidated( address indexed _collateral, address indexed _reserve, address indexed _user, uint256 _feeLiquidated, uint256 _liquidatedCollateralForFee, uint256 _timestamp ); /** * @dev emitted when a borrower is liquidated * @param _collateral the address of the collateral being liquidated * @param _reserve the address of the reserve * @param _user the address of the user being liquidated * @param _purchaseAmount the total amount liquidated * @param _liquidatedCollateralAmount the amount of collateral being liquidated * @param _accruedBorrowInterest the amount of interest accrued by the borrower since the last action * @param _liquidator the address of the liquidator * @param _receiveAToken true if the liquidator wants to receive aTokens, false otherwise * @param _timestamp the timestamp of the action **/ event LiquidationCall( address indexed _collateral, address indexed _reserve, address indexed _user, uint256 _purchaseAmount, uint256 _liquidatedCollateralAmount, uint256 _accruedBorrowInterest, address _liquidator, bool _receiveAToken, uint256 _timestamp ); /** * @dev functions affected by this modifier can only be invoked by the * aToken.sol contract * @param _reserve the address of the reserve **/ modifier onlyOverlyingAToken(address _reserve) { require( msg.sender == core.getReserveATokenAddress(_reserve), "The caller of this function can only be the aToken contract of this reserve" ); _; } /** * @dev functions affected by this modifier can only be invoked if the reserve is active * @param _reserve the address of the reserve **/ modifier onlyActiveReserve(address _reserve) { requireReserveActiveInternal(_reserve); _; } /** * @dev functions affected by this modifier can only be invoked if the reserve is not freezed. * A freezed reserve only allows redeems, repays, rebalances and liquidations. * @param _reserve the address of the reserve **/ modifier onlyUnfreezedReserve(address _reserve) { requireReserveNotFreezedInternal(_reserve); _; } /** * @dev functions affected by this modifier can only be invoked if the provided _amount input parameter * is not zero. * @param _amount the amount provided **/ modifier onlyAmountGreaterThanZero(uint256 _amount) { requireAmountGreaterThanZeroInternal(_amount); _; } uint256 public constant UINT_MAX_VALUE = uint256(-1); uint256 public constant LENDINGPOOL_REVISION = 0x3; function getRevision() internal pure returns (uint256) { return LENDINGPOOL_REVISION; } /** * @dev this function is invoked by the proxy contract when the LendingPool contract is added to the * AddressesProvider. * @param _addressesProvider the address of the LendingPoolAddressesProvider registry **/ function initialize(LendingPoolAddressesProvider _addressesProvider) public initializer { addressesProvider = _addressesProvider; core = LendingPoolCore(addressesProvider.getLendingPoolCore()); dataProvider = LendingPoolDataProvider(addressesProvider.getLendingPoolDataProvider()); parametersProvider = LendingPoolParametersProvider( addressesProvider.getLendingPoolParametersProvider() ); feeProvider = IFeeProvider(addressesProvider.getFeeProvider()); } /** * @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens) * is minted. * @param _reserve the address of the reserve * @param _amount the amount to be deposited * @param _referralCode integrators are assigned a referral code and can potentially receive rewards. **/ function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external payable nonReentrant onlyActiveReserve(_reserve) onlyUnfreezedReserve(_reserve) onlyAmountGreaterThanZero(_amount) { AToken aToken = AToken(core.getReserveATokenAddress(_reserve)); bool isFirstDeposit = aToken.balanceOf(msg.sender) == 0; core.updateStateOnDeposit(_reserve, msg.sender, _amount, isFirstDeposit); //minting AToken to user 1:1 with the specific exchange rate aToken.mintOnDeposit(msg.sender, _amount); //transfer to the core contract core.transferToReserve.value(msg.value)(_reserve, msg.sender, _amount); //solium-disable-next-line emit Deposit(_reserve, msg.sender, _amount, _referralCode, block.timestamp); } /** * @dev Redeems the underlying amount of assets requested by _user. * This function is executed by the overlying aToken contract in response to a redeem action. * @param _reserve the address of the reserve * @param _user the address of the user performing the action * @param _amount the underlying amount to be redeemed **/ function redeemUnderlying( address _reserve, address payable _user, uint256 _amount, uint256 _aTokenBalanceAfterRedeem ) external nonReentrant onlyOverlyingAToken(_reserve) onlyActiveReserve(_reserve) onlyAmountGreaterThanZero(_amount) { uint256 currentAvailableLiquidity = core.getReserveAvailableLiquidity(_reserve); require( currentAvailableLiquidity >= _amount, "There is not enough liquidity available to redeem" ); core.updateStateOnRedeem(_reserve, _user, _amount, _aTokenBalanceAfterRedeem == 0); core.transferToUser(_reserve, _user, _amount); //solium-disable-next-line emit RedeemUnderlying(_reserve, _user, _amount, block.timestamp); } /** * @dev data structures for local computations in the borrow() method. */ struct BorrowLocalVars { uint256 principalBorrowBalance; uint256 currentLtv; uint256 currentLiquidationThreshold; uint256 borrowFee; uint256 requestedBorrowAmountETH; uint256 amountOfCollateralNeededETH; uint256 userCollateralBalanceETH; uint256 userBorrowBalanceETH; uint256 userTotalFeesETH; uint256 borrowBalanceIncrease; uint256 currentReserveStableRate; uint256 availableLiquidity; uint256 reserveDecimals; uint256 finalUserBorrowRate; CoreLibrary.InterestRateMode rateMode; bool healthFactorBelowThreshold; } /** * @dev Allows users to borrow a specific amount of the reserve currency, provided that the borrower * already deposited enough collateral. * @param _reserve the address of the reserve * @param _amount the amount to be borrowed * @param _interestRateMode the interest rate mode at which the user wants to borrow. Can be 0 (STABLE) or 1 (VARIABLE) **/ function borrow( address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode ) external nonReentrant onlyActiveReserve(_reserve) onlyUnfreezedReserve(_reserve) onlyAmountGreaterThanZero(_amount) { // Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables BorrowLocalVars memory vars; //check that the reserve is enabled for borrowing require(core.isReserveBorrowingEnabled(_reserve), "Reserve is not enabled for borrowing"); //validate interest rate mode require( uint256(CoreLibrary.InterestRateMode.VARIABLE) == _interestRateMode || uint256(CoreLibrary.InterestRateMode.STABLE) == _interestRateMode, "Invalid interest rate mode selected" ); //cast the rateMode to coreLibrary.interestRateMode vars.rateMode = CoreLibrary.InterestRateMode(_interestRateMode); //check that the amount is available in the reserve vars.availableLiquidity = core.getReserveAvailableLiquidity(_reserve); require( vars.availableLiquidity >= _amount, "There is not enough liquidity available in the reserve" ); ( , vars.userCollateralBalanceETH, vars.userBorrowBalanceETH, vars.userTotalFeesETH, vars.currentLtv, vars.currentLiquidationThreshold, , vars.healthFactorBelowThreshold ) = dataProvider.calculateUserGlobalData(msg.sender); require(vars.userCollateralBalanceETH > 0, "The collateral balance is 0"); require( !vars.healthFactorBelowThreshold, "The borrower can already be liquidated so he cannot borrow more" ); //calculating fees vars.borrowFee = feeProvider.calculateLoanOriginationFee(msg.sender, _amount); require(vars.borrowFee > 0, "The amount to borrow is too small"); vars.amountOfCollateralNeededETH = dataProvider.calculateCollateralNeededInETH( _reserve, _amount, vars.borrowFee, vars.userBorrowBalanceETH, vars.userTotalFeesETH, vars.currentLtv ); require( vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH, "There is not enough collateral to cover a new borrow" ); /** * Following conditions need to be met if the user is borrowing at a stable rate: * 1. Reserve must be enabled for stable rate borrowing * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency * they are borrowing, to prevent abuses. * 3. Users will be able to borrow only a relatively small, configurable amount of the total * liquidity **/ if (vars.rateMode == CoreLibrary.InterestRateMode.STABLE) { //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve require( core.isUserAllowedToBorrowAtStable(_reserve, msg.sender, _amount), "User cannot borrow the selected amount with a stable rate" ); //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanPercent = parametersProvider.getMaxStableRateBorrowSizePercent(); uint256 maxLoanSizeStable = vars.availableLiquidity.mul(maxLoanPercent).div(100); require( _amount <= maxLoanSizeStable, "User is trying to borrow too much liquidity at a stable rate" ); } //all conditions passed - borrow is accepted (vars.finalUserBorrowRate, vars.borrowBalanceIncrease) = core.updateStateOnBorrow( _reserve, msg.sender, _amount, vars.borrowFee, vars.rateMode ); //if we reached this point, we can transfer core.transferToUser(_reserve, msg.sender, _amount); emit Borrow( _reserve, msg.sender, _amount, _interestRateMode, vars.finalUserBorrowRate, vars.borrowFee, vars.borrowBalanceIncrease, _referralCode, //solium-disable-next-line block.timestamp ); } /** * @notice repays a borrow on the specific reserve, for the specified amount (or for the whole amount, if uint256(-1) is specified). * @dev the target user is defined by _onBehalfOf. If there is no repayment on behalf of another account, * _onBehalfOf must be equal to msg.sender. * @param _reserve the address of the reserve on which the user borrowed * @param _amount the amount to repay, or uint256(-1) if the user wants to repay everything * @param _onBehalfOf the address for which msg.sender is repaying. **/ struct RepayLocalVars { uint256 principalBorrowBalance; uint256 compoundedBorrowBalance; uint256 borrowBalanceIncrease; bool isETH; uint256 paybackAmount; uint256 paybackAmountMinusFees; uint256 currentStableRate; uint256 originationFee; } function repay(address _reserve, uint256 _amount, address payable _onBehalfOf) external payable nonReentrant onlyActiveReserve(_reserve) onlyAmountGreaterThanZero(_amount) { // Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables RepayLocalVars memory vars; ( vars.principalBorrowBalance, vars.compoundedBorrowBalance, vars.borrowBalanceIncrease ) = core.getUserBorrowBalances(_reserve, _onBehalfOf); vars.originationFee = core.getUserOriginationFee(_reserve, _onBehalfOf); vars.isETH = EthAddressLib.ethAddress() == _reserve; require(vars.compoundedBorrowBalance > 0, "The user does not have any borrow pending"); require( _amount != UINT_MAX_VALUE || msg.sender == _onBehalfOf, "To repay on behalf of an user an explicit amount to repay is needed." ); //default to max amount vars.paybackAmount = vars.compoundedBorrowBalance.add(vars.originationFee); if (_amount != UINT_MAX_VALUE && _amount < vars.paybackAmount) { vars.paybackAmount = _amount; } require( !vars.isETH || msg.value >= vars.paybackAmount, "Invalid msg.value sent for the repayment" ); //if the amount is smaller than the origination fee, just transfer the amount to the fee destination address if (vars.paybackAmount <= vars.originationFee) { core.updateStateOnRepay( _reserve, _onBehalfOf, 0, vars.paybackAmount, vars.borrowBalanceIncrease, false ); core.transferToFeeCollectionAddress.value(vars.isETH ? vars.paybackAmount : 0)( _reserve, _onBehalfOf, vars.paybackAmount, addressesProvider.getTokenDistributor() ); emit Repay( _reserve, _onBehalfOf, msg.sender, 0, vars.paybackAmount, vars.borrowBalanceIncrease, //solium-disable-next-line block.timestamp ); return; } vars.paybackAmountMinusFees = vars.paybackAmount.sub(vars.originationFee); core.updateStateOnRepay( _reserve, _onBehalfOf, vars.paybackAmountMinusFees, vars.originationFee, vars.borrowBalanceIncrease, vars.compoundedBorrowBalance == vars.paybackAmountMinusFees ); //if the user didn't repay the origination fee, transfer the fee to the fee collection address if(vars.originationFee > 0) { core.transferToFeeCollectionAddress.value(vars.isETH ? vars.originationFee : 0)( _reserve, _onBehalfOf, vars.originationFee, addressesProvider.getTokenDistributor() ); } //sending the total msg.value if the transfer is ETH. //the transferToReserve() function will take care of sending the //excess ETH back to the caller core.transferToReserve.value(vars.isETH ? msg.value.sub(vars.originationFee) : 0)( _reserve, msg.sender, vars.paybackAmountMinusFees ); emit Repay( _reserve, _onBehalfOf, msg.sender, vars.paybackAmountMinusFees, vars.originationFee, vars.borrowBalanceIncrease, //solium-disable-next-line block.timestamp ); } /** * @dev borrowers can user this function to swap between stable and variable borrow rate modes. * @param _reserve the address of the reserve on which the user borrowed **/ function swapBorrowRateMode(address _reserve) external nonReentrant onlyActiveReserve(_reserve) onlyUnfreezedReserve(_reserve) { (uint256 principalBorrowBalance, uint256 compoundedBorrowBalance, uint256 borrowBalanceIncrease) = core .getUserBorrowBalances(_reserve, msg.sender); require( compoundedBorrowBalance > 0, "User does not have a borrow in progress on this reserve" ); CoreLibrary.InterestRateMode currentRateMode = core.getUserCurrentBorrowRateMode( _reserve, msg.sender ); if (currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) { /** * user wants to swap to stable, before swapping we need to ensure that * 1. stable borrow rate is enabled on the reserve * 2. user is not trying to abuse the reserve by depositing * more collateral than he is borrowing, artificially lowering * the interest rate, borrowing at variable, and switching to stable **/ require( core.isUserAllowedToBorrowAtStable(_reserve, msg.sender, compoundedBorrowBalance), "User cannot borrow the selected amount at stable" ); } (CoreLibrary.InterestRateMode newRateMode, uint256 newBorrowRate) = core .updateStateOnSwapRate( _reserve, msg.sender, principalBorrowBalance, compoundedBorrowBalance, borrowBalanceIncrease, currentRateMode ); emit Swap( _reserve, msg.sender, uint256(newRateMode), newBorrowRate, borrowBalanceIncrease, //solium-disable-next-line block.timestamp ); } /** * @dev rebalances the stable interest rate of a user if current liquidity rate > user stable rate. * this is regulated by Aave to ensure that the protocol is not abused, and the user is paying a fair * rate. The rebalance mechanism is updated in the context of the V1 -> V2 transition to automatically switch the user to variable. * @param _reserve the address of the reserve * @param _user the address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address _reserve, address _user) external nonReentrant onlyActiveReserve(_reserve) { (uint256 principalBalance, uint256 compoundedBalance, uint256 borrowBalanceIncrease) = core.getUserBorrowBalances( _reserve, _user ); //step 1: user must be borrowing on _reserve at a stable rate require(compoundedBalance > 0, "User does not have any borrow for this reserve"); CoreLibrary.InterestRateMode rateMode = core.getUserCurrentBorrowRateMode(_reserve, _user); require( rateMode == CoreLibrary.InterestRateMode.STABLE, "The user borrow is variable and cannot be rebalanced" ); uint256 userCurrentStableRate = core.getUserCurrentStableBorrowRate(_reserve, _user); uint256 liquidityRate = core.getReserveCurrentLiquidityRate(_reserve); if (userCurrentStableRate < liquidityRate) { (CoreLibrary.InterestRateMode newRateMode, uint256 newBorrowRate) = core .updateStateOnSwapRate( _reserve, _user, principalBalance, compoundedBalance, borrowBalanceIncrease, rateMode ); emit Swap( _reserve, _user, uint256(newRateMode), newBorrowRate, borrowBalanceIncrease, //solium-disable-next-line block.timestamp ); } revert("Interest rate rebalance conditions were not met"); } /** * @dev allows depositors to enable or disable a specific deposit as collateral. * @param _reserve the address of the reserve * @param _useAsCollateral true if the user wants to user the deposit as collateral, false otherwise. **/ function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external nonReentrant onlyActiveReserve(_reserve) onlyUnfreezedReserve(_reserve) { uint256 underlyingBalance = core.getUserUnderlyingAssetBalance(_reserve, msg.sender); require(underlyingBalance > 0, "User does not have any liquidity deposited"); require( dataProvider.balanceDecreaseAllowed(_reserve, msg.sender, underlyingBalance), "User deposit is already being used as collateral" ); core.setUserUseReserveAsCollateral(_reserve, msg.sender, _useAsCollateral); if (_useAsCollateral) { emit ReserveUsedAsCollateralEnabled(_reserve, msg.sender); } else { emit ReserveUsedAsCollateralDisabled(_reserve, msg.sender); } } /** * @dev users can invoke this function to liquidate an undercollateralized position. * @param _reserve the address of the collateral to liquidated * @param _reserve the address of the principal reserve * @param _user the address of the borrower * @param _purchaseAmount the amount of principal that the liquidator wants to repay * @param _receiveAToken true if the liquidators wants to receive the aTokens, false if * he wants to receive the underlying asset directly **/ function liquidationCall( address _collateral, address _reserve, address _user, uint256 _purchaseAmount, bool _receiveAToken ) external payable nonReentrant onlyActiveReserve(_reserve) onlyActiveReserve(_collateral) { address liquidationManager = addressesProvider.getLendingPoolLiquidationManager(); //solium-disable-next-line (bool success, bytes memory result) = liquidationManager.delegatecall( abi.encodeWithSignature( "liquidationCall(address,address,address,uint256,bool)", _collateral, _reserve, _user, _purchaseAmount, _receiveAToken ) ); require(success, "Liquidation call failed"); (uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string)); if (returnCode != 0) { //error found revert(string(abi.encodePacked("Liquidation failed: ", returnMessage))); } } /** * @dev allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. NOTE There are security concerns for developers of flashloan receiver contracts * that must be kept into consideration. For further details please visit https://developers.aave.com * @param _receiver The address of the contract receiving the funds. The receiver should implement the IFlashLoanReceiver interface. * @param _reserve the address of the principal reserve * @param _amount the amount requested for this flashloan **/ function flashLoan(address _receiver, address _reserve, uint256 _amount, bytes memory _params) public nonReentrant onlyActiveReserve(_reserve) onlyAmountGreaterThanZero(_amount) { //check that the reserve has enough available liquidity //we avoid using the getAvailableLiquidity() function in LendingPoolCore to save gas uint256 availableLiquidityBefore = _reserve == EthAddressLib.ethAddress() ? address(core).balance : IERC20(_reserve).balanceOf(address(core)); require( availableLiquidityBefore >= _amount, "There is not enough liquidity available to borrow" ); (uint256 totalFeeBips, uint256 protocolFeeBips) = parametersProvider .getFlashLoanFeesInBips(); //calculate amount fee uint256 amountFee = _amount.mul(totalFeeBips).div(10000); //protocol fee is the part of the amountFee reserved for the protocol - the rest goes to depositors uint256 protocolFee = amountFee.mul(protocolFeeBips).div(10000); require( amountFee > 0 && protocolFee > 0, "The requested amount is too small for a flashLoan." ); //get the FlashLoanReceiver instance IFlashLoanReceiver receiver = IFlashLoanReceiver(_receiver); address payable userPayable = address(uint160(_receiver)); //transfer funds to the receiver core.transferToUser(_reserve, userPayable, _amount); //execute action of the receiver receiver.executeOperation(_reserve, _amount, amountFee, _params); //check that the actual balance of the core contract includes the returned amount uint256 availableLiquidityAfter = _reserve == EthAddressLib.ethAddress() ? address(core).balance : IERC20(_reserve).balanceOf(address(core)); require( availableLiquidityAfter == availableLiquidityBefore.add(amountFee), "The actual balance of the protocol is inconsistent" ); core.updateStateOnFlashLoan( _reserve, availableLiquidityBefore, amountFee.sub(protocolFee), protocolFee ); //solium-disable-next-line emit FlashLoan(_receiver, _reserve, _amount, amountFee, protocolFee, block.timestamp); } /** * @dev accessory functions to fetch data from the core contract **/ function getReserveConfigurationData(address _reserve) external view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address interestRateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ) { return dataProvider.getReserveConfigurationData(_reserve); } function getReserveData(address _reserve) external view returns ( uint256 totalLiquidity, uint256 availableLiquidity, uint256 totalBorrowsStable, uint256 totalBorrowsVariable, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 utilizationRate, uint256 liquidityIndex, uint256 variableBorrowIndex, address aTokenAddress, uint40 lastUpdateTimestamp ) { return dataProvider.getReserveData(_reserve); } function getUserAccountData(address _user) external view returns ( uint256 totalLiquidityETH, uint256 totalCollateralETH, uint256 totalBorrowsETH, uint256 totalFeesETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) { return dataProvider.getUserAccountData(_user); } function getUserReserveData(address _reserve, address _user) external view returns ( uint256 currentATokenBalance, uint256 currentBorrowBalance, uint256 principalBorrowBalance, uint256 borrowRateMode, uint256 borrowRate, uint256 liquidityRate, uint256 originationFee, uint256 variableBorrowIndex, uint256 lastUpdateTimestamp, bool usageAsCollateralEnabled ) { return dataProvider.getUserReserveData(_reserve, _user); } function getReserves() external view returns (address[] memory) { return core.getReserves(); } /** * @dev internal function to save on code size for the onlyActiveReserve modifier **/ function requireReserveActiveInternal(address _reserve) internal view { require(core.getReserveIsActive(_reserve), "Action requires an active reserve"); } /** * @notice internal function to save on code size for the onlyUnfreezedReserve modifier **/ function requireReserveNotFreezedInternal(address _reserve) internal view { require(!core.getReserveIsFreezed(_reserve), "Action requires an unfreezed reserve"); } /** * @notice internal function to save on code size for the onlyAmountGreaterThanZero modifier **/ function requireAmountGreaterThanZeroInternal(uint256 _amount) internal pure { require(_amount > 0, "Amount must be greater than 0"); } } /** * @title LendingPoolCore contract * @author Aave * @notice Holds the state of the lending pool and all the funds deposited * @dev NOTE: The core does not enforce security checks on the update of the state * (eg, updateStateOnBorrow() does not enforce that borrowed is enabled on the reserve). * The check that an action can be performed is a duty of the overlying LendingPool contract. **/ contract LendingPoolCore is VersionedInitializable { using SafeMath for uint256; using WadRayMath for uint256; using CoreLibrary for CoreLibrary.ReserveData; using CoreLibrary for CoreLibrary.UserReserveData; using SafeERC20 for ERC20; using Address for address payable; /** * @dev Emitted when the state of a reserve is updated * @param reserve the address of the reserve * @param liquidityRate the new liquidity rate * @param stableBorrowRate the new stable borrow rate * @param variableBorrowRate the new variable borrow rate * @param liquidityIndex the new liquidity index * @param variableBorrowIndex the new variable borrow index **/ event ReserveUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); address public lendingPoolAddress; LendingPoolAddressesProvider public addressesProvider; /** * @dev only lending pools can use functions affected by this modifier **/ modifier onlyLendingPool { require(lendingPoolAddress == msg.sender, "The caller must be a lending pool contract"); _; } /** * @dev only lending pools configurator can use functions affected by this modifier **/ modifier onlyLendingPoolConfigurator { require( addressesProvider.getLendingPoolConfigurator() == msg.sender, "The caller must be a lending pool configurator contract" ); _; } mapping(address => CoreLibrary.ReserveData) internal reserves; mapping(address => mapping(address => CoreLibrary.UserReserveData)) internal usersReserveData; address[] public reservesList; uint256 public constant CORE_REVISION = 0x7; /** * @dev returns the revision number of the contract **/ function getRevision() internal pure returns (uint256) { return CORE_REVISION; } /** * @dev initializes the Core contract, invoked upon registration on the AddressesProvider * @param _addressesProvider the addressesProvider contract **/ function initialize(LendingPoolAddressesProvider _addressesProvider) public initializer { addressesProvider = _addressesProvider; refreshConfigInternal(); } /** * @dev updates the state of the core as a result of a deposit action * @param _reserve the address of the reserve in which the deposit is happening * @param _user the address of the the user depositing * @param _amount the amount being deposited * @param _isFirstDeposit true if the user is depositing for the first time **/ function updateStateOnDeposit( address _reserve, address _user, uint256 _amount, bool _isFirstDeposit ) external onlyLendingPool { reserves[_reserve].updateCumulativeIndexes(); updateReserveInterestRatesAndTimestampInternal(_reserve, _amount, 0); if (_isFirstDeposit) { //if this is the first deposit of the user, we configure the deposit as enabled to be used as collateral setUserUseReserveAsCollateral(_reserve, _user, true); } } /** * @dev updates the state of the core as a result of a redeem action * @param _reserve the address of the reserve in which the redeem is happening * @param _user the address of the the user redeeming * @param _amountRedeemed the amount being redeemed * @param _userRedeemedEverything true if the user is redeeming everything **/ function updateStateOnRedeem( address _reserve, address _user, uint256 _amountRedeemed, bool _userRedeemedEverything ) external onlyLendingPool { //compound liquidity and variable borrow interests reserves[_reserve].updateCumulativeIndexes(); updateReserveInterestRatesAndTimestampInternal(_reserve, 0, _amountRedeemed); //if user redeemed everything the useReserveAsCollateral flag is reset if (_userRedeemedEverything) { setUserUseReserveAsCollateral(_reserve, _user, false); } } /** * @dev updates the state of the core as a result of a flashloan action * @param _reserve the address of the reserve in which the flashloan is happening * @param _income the income of the protocol as a result of the action **/ function updateStateOnFlashLoan( address _reserve, uint256 _availableLiquidityBefore, uint256 _income, uint256 _protocolFee ) external onlyLendingPool { transferFlashLoanProtocolFeeInternal(_reserve, _protocolFee); //compounding the cumulated interest reserves[_reserve].updateCumulativeIndexes(); uint256 totalLiquidityBefore = _availableLiquidityBefore.add( getReserveTotalBorrows(_reserve) ); //compounding the received fee into the reserve reserves[_reserve].cumulateToLiquidityIndex(totalLiquidityBefore, _income); //refresh interest rates updateReserveInterestRatesAndTimestampInternal(_reserve, _income, 0); } /** * @dev updates the state of the core as a consequence of a borrow action. * @param _reserve the address of the reserve on which the user is borrowing * @param _user the address of the borrower * @param _amountBorrowed the new amount borrowed * @param _borrowFee the fee on the amount borrowed * @param _rateMode the borrow rate mode (stable, variable) * @return the new borrow rate for the user **/ function updateStateOnBorrow( address _reserve, address _user, uint256 _amountBorrowed, uint256 _borrowFee, CoreLibrary.InterestRateMode _rateMode ) external onlyLendingPool returns (uint256, uint256) { // getting the previous borrow data of the user (uint256 principalBorrowBalance, , uint256 balanceIncrease) = getUserBorrowBalances( _reserve, _user ); updateReserveStateOnBorrowInternal( _reserve, _user, principalBorrowBalance, balanceIncrease, _amountBorrowed, _rateMode ); updateUserStateOnBorrowInternal( _reserve, _user, _amountBorrowed, balanceIncrease, _borrowFee, _rateMode ); updateReserveInterestRatesAndTimestampInternal(_reserve, 0, _amountBorrowed); return (getUserCurrentBorrowRate(_reserve, _user), balanceIncrease); } /** * @dev updates the state of the core as a consequence of a repay action. * @param _reserve the address of the reserve on which the user is repaying * @param _user the address of the borrower * @param _paybackAmountMinusFees the amount being paid back minus fees * @param _originationFeeRepaid the fee on the amount that is being repaid * @param _balanceIncrease the accrued interest on the borrowed amount * @param _repaidWholeLoan true if the user is repaying the whole loan **/ function updateStateOnRepay( address _reserve, address _user, uint256 _paybackAmountMinusFees, uint256 _originationFeeRepaid, uint256 _balanceIncrease, bool _repaidWholeLoan ) external onlyLendingPool { updateReserveStateOnRepayInternal( _reserve, _user, _paybackAmountMinusFees, _balanceIncrease ); updateUserStateOnRepayInternal( _reserve, _user, _paybackAmountMinusFees, _originationFeeRepaid, _balanceIncrease, _repaidWholeLoan ); updateReserveInterestRatesAndTimestampInternal(_reserve, _paybackAmountMinusFees, 0); } /** * @dev updates the state of the core as a consequence of a swap rate action. * @param _reserve the address of the reserve on which the user is repaying * @param _user the address of the borrower * @param _principalBorrowBalance the amount borrowed by the user * @param _compoundedBorrowBalance the amount borrowed plus accrued interest * @param _balanceIncrease the accrued interest on the borrowed amount * @param _currentRateMode the current interest rate mode for the user **/ function updateStateOnSwapRate( address _reserve, address _user, uint256 _principalBorrowBalance, uint256 _compoundedBorrowBalance, uint256 _balanceIncrease, CoreLibrary.InterestRateMode _currentRateMode ) external onlyLendingPool returns (CoreLibrary.InterestRateMode, uint256) { updateReserveStateOnSwapRateInternal( _reserve, _user, _principalBorrowBalance, _compoundedBorrowBalance, _currentRateMode ); CoreLibrary.InterestRateMode newRateMode = updateUserStateOnSwapRateInternal( _reserve, _user, _balanceIncrease, _currentRateMode ); updateReserveInterestRatesAndTimestampInternal(_reserve, 0, 0); return (newRateMode, getUserCurrentBorrowRate(_reserve, _user)); } /** * @dev updates the state of the core as a consequence of a liquidation action. * @param _principalReserve the address of the principal reserve that is being repaid * @param _collateralReserve the address of the collateral reserve that is being liquidated * @param _user the address of the borrower * @param _amountToLiquidate the amount being repaid by the liquidator * @param _collateralToLiquidate the amount of collateral being liquidated * @param _feeLiquidated the amount of origination fee being liquidated * @param _liquidatedCollateralForFee the amount of collateral equivalent to the origination fee + bonus * @param _balanceIncrease the accrued interest on the borrowed amount * @param _liquidatorReceivesAToken true if the liquidator will receive aTokens, false otherwise **/ function updateStateOnLiquidation( address _principalReserve, address _collateralReserve, address _user, uint256 _amountToLiquidate, uint256 _collateralToLiquidate, uint256 _feeLiquidated, uint256 _liquidatedCollateralForFee, uint256 _balanceIncrease, bool _liquidatorReceivesAToken ) external onlyLendingPool { updatePrincipalReserveStateOnLiquidationInternal( _principalReserve, _user, _amountToLiquidate, _balanceIncrease ); updateCollateralReserveStateOnLiquidationInternal( _collateralReserve ); updateUserStateOnLiquidationInternal( _principalReserve, _user, _amountToLiquidate, _feeLiquidated, _balanceIncrease ); updateReserveInterestRatesAndTimestampInternal(_principalReserve, _amountToLiquidate, 0); if (!_liquidatorReceivesAToken) { updateReserveInterestRatesAndTimestampInternal( _collateralReserve, 0, _collateralToLiquidate.add(_liquidatedCollateralForFee) ); } } /** * @dev updates the state of the core as a consequence of a stable rate rebalance * @param _reserve the address of the principal reserve where the user borrowed * @param _user the address of the borrower * @param _balanceIncrease the accrued interest on the borrowed amount * @return the new stable rate for the user **/ function updateStateOnRebalance(address _reserve, address _user, uint256 _balanceIncrease) external onlyLendingPool returns (uint256) { updateReserveStateOnRebalanceInternal(_reserve, _user, _balanceIncrease); //update user data and rebalance the rate updateUserStateOnRebalanceInternal(_reserve, _user, _balanceIncrease); updateReserveInterestRatesAndTimestampInternal(_reserve, 0, 0); return usersReserveData[_user][_reserve].stableBorrowRate; } /** * @dev enables or disables a reserve as collateral * @param _reserve the address of the principal reserve where the user deposited * @param _user the address of the depositor * @param _useAsCollateral true if the depositor wants to use the reserve as collateral **/ function setUserUseReserveAsCollateral(address _reserve, address _user, bool _useAsCollateral) public onlyLendingPool { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; user.useAsCollateral = _useAsCollateral; } /** * @notice ETH/token transfer functions **/ /** * @dev fallback function enforces that the caller is a contract, to support flashloan transfers **/ function() external payable { //only contracts can send ETH to the core require(msg.sender.isContract(), "Only contracts can send ether to the Lending pool core"); } /** * @dev transfers to the user a specific amount from the reserve. * @param _reserve the address of the reserve where the transfer is happening * @param _user the address of the user receiving the transfer * @param _amount the amount being transferred **/ function transferToUser(address _reserve, address payable _user, uint256 _amount) external onlyLendingPool { if (_reserve != EthAddressLib.ethAddress()) { ERC20(_reserve).safeTransfer(_user, _amount); } else { //solium-disable-next-line (bool result, ) = _user.call.value(_amount).gas(50000)(""); require(result, "Transfer of ETH failed"); } } /** * @dev transfers the protocol fees to the fees collection address * @param _token the address of the token being transferred * @param _user the address of the user from where the transfer is happening * @param _amount the amount being transferred * @param _destination the fee receiver address **/ function transferToFeeCollectionAddress( address _token, address _user, uint256 _amount, address _destination ) external payable onlyLendingPool { address payable feeAddress = address(uint160(_destination)); //cast the address to payable if (_token != EthAddressLib.ethAddress()) { require( msg.value == 0, "User is sending ETH along with the ERC20 transfer. Check the value attribute of the transaction" ); ERC20(_token).safeTransferFrom(_user, feeAddress, _amount); } else { require(msg.value >= _amount, "The amount and the value sent to deposit do not match"); //solium-disable-next-line (bool result, ) = feeAddress.call.value(_amount).gas(50000)(""); require(result, "Transfer of ETH failed"); } } /** * @dev transfers the fees to the fees collection address in the case of liquidation * @param _token the address of the token being transferred * @param _amount the amount being transferred * @param _destination the fee receiver address **/ function liquidateFee( address _token, uint256 _amount, address _destination ) external payable onlyLendingPool { address payable feeAddress = address(uint160(_destination)); //cast the address to payable require( msg.value == 0, "Fee liquidation does not require any transfer of value" ); if (_token != EthAddressLib.ethAddress()) { ERC20(_token).safeTransfer(feeAddress, _amount); } else { //solium-disable-next-line (bool result, ) = feeAddress.call.value(_amount).gas(50000)(""); require(result, "Transfer of ETH failed"); } } /** * @dev transfers an amount from a user to the destination reserve * @param _reserve the address of the reserve where the amount is being transferred * @param _user the address of the user from where the transfer is happening * @param _amount the amount being transferred **/ function transferToReserve(address _reserve, address payable _user, uint256 _amount) external payable onlyLendingPool { if (_reserve != EthAddressLib.ethAddress()) { require(msg.value == 0, "User is sending ETH along with the ERC20 transfer."); ERC20(_reserve).safeTransferFrom(_user, address(this), _amount); } else { require(msg.value >= _amount, "The amount and the value sent to deposit do not match"); if (msg.value > _amount) { //send back excess ETH uint256 excessAmount = msg.value.sub(_amount); //solium-disable-next-line (bool result, ) = _user.call.value(excessAmount).gas(50000)(""); require(result, "Transfer of ETH failed"); } } } /** * @notice data access functions **/ /** * @dev returns the basic data (balances, fee accrued, reserve enabled/disabled as collateral) * needed to calculate the global account data in the LendingPoolDataProvider * @param _reserve the address of the reserve * @param _user the address of the user * @return the user deposited balance, the principal borrow balance, the fee, and if the reserve is enabled as collateral or not **/ function getUserBasicReserveData(address _reserve, address _user) external view returns (uint256, uint256, uint256, bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; uint256 underlyingBalance = getUserUnderlyingAssetBalance(_reserve, _user); if (user.principalBorrowBalance == 0) { return (underlyingBalance, 0, 0, user.useAsCollateral); } return ( underlyingBalance, user.getCompoundedBorrowBalance(reserve), user.originationFee, user.useAsCollateral ); } /** * @dev checks if a user is allowed to borrow at a stable rate * @param _reserve the reserve address * @param _user the user * @param _amount the amount the the user wants to borrow * @return true if the user is allowed to borrow at a stable rate, false otherwise **/ function isUserAllowedToBorrowAtStable(address _reserve, address _user, uint256 _amount) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; if (!reserve.isStableBorrowRateEnabled) return false; return !user.useAsCollateral || !reserve.usageAsCollateralEnabled || _amount > getUserUnderlyingAssetBalance(_reserve, _user); } /** * @dev gets the underlying asset balance of a user based on the corresponding aToken balance. * @param _reserve the reserve address * @param _user the user address * @return the underlying deposit balance of the user **/ function getUserUnderlyingAssetBalance(address _reserve, address _user) public view returns (uint256) { AToken aToken = AToken(reserves[_reserve].aTokenAddress); return aToken.balanceOf(_user); } /** * @dev gets the interest rate strategy contract address for the reserve * @param _reserve the reserve address * @return the address of the interest rate strategy contract **/ function getReserveInterestRateStrategyAddress(address _reserve) public view returns (address) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.interestRateStrategyAddress; } /** * @dev gets the aToken contract address for the reserve * @param _reserve the reserve address * @return the address of the aToken contract **/ function getReserveATokenAddress(address _reserve) public view returns (address) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.aTokenAddress; } /** * @dev gets the available liquidity in the reserve. The available liquidity is the balance of the core contract * @param _reserve the reserve address * @return the available liquidity **/ function getReserveAvailableLiquidity(address _reserve) public view returns (uint256) { uint256 balance = 0; if (_reserve == EthAddressLib.ethAddress()) { balance = address(this).balance; } else { balance = IERC20(_reserve).balanceOf(address(this)); } return balance; } /** * @dev gets the total liquidity in the reserve. The total liquidity is the balance of the core contract + total borrows * @param _reserve the reserve address * @return the total liquidity **/ function getReserveTotalLiquidity(address _reserve) public view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return getReserveAvailableLiquidity(_reserve).add(reserve.getTotalBorrows()); } /** * @dev gets the normalized income of the reserve. a value of 1e27 means there is no income. A value of 2e27 means there * there has been 100% income. * @param _reserve the reserve address * @return the reserve normalized income **/ function getReserveNormalizedIncome(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.getNormalizedIncome(); } /** * @dev gets the reserve total borrows * @param _reserve the reserve address * @return the total borrows (stable + variable) **/ function getReserveTotalBorrows(address _reserve) public view returns (uint256) { return reserves[_reserve].getTotalBorrows(); } /** * @dev gets the reserve total borrows stable * @param _reserve the reserve address * @return the total borrows stable **/ function getReserveTotalBorrowsStable(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.totalBorrowsStable; } /** * @dev gets the reserve total borrows variable * @param _reserve the reserve address * @return the total borrows variable **/ function getReserveTotalBorrowsVariable(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.totalBorrowsVariable; } /** * @dev gets the reserve liquidation threshold * @param _reserve the reserve address * @return the reserve liquidation threshold **/ function getReserveLiquidationThreshold(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.liquidationThreshold; } /** * @dev gets the reserve liquidation bonus * @param _reserve the reserve address * @return the reserve liquidation bonus **/ function getReserveLiquidationBonus(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.liquidationBonus; } /** * @dev gets the reserve current variable borrow rate. Is the base variable borrow rate if the reserve is empty * @param _reserve the reserve address * @return the reserve current variable borrow rate **/ function getReserveCurrentVariableBorrowRate(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; if (reserve.currentVariableBorrowRate == 0) { return IReserveInterestRateStrategy(reserve.interestRateStrategyAddress) .getBaseVariableBorrowRate(); } return reserve.currentVariableBorrowRate; } /** * @dev gets the reserve current stable borrow rate. Is the market rate if the reserve is empty * @param _reserve the reserve address * @return the reserve current stable borrow rate **/ function getReserveCurrentStableBorrowRate(address _reserve) public view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; ILendingRateOracle oracle = ILendingRateOracle(addressesProvider.getLendingRateOracle()); if (reserve.currentStableBorrowRate == 0) { //no stable rate borrows yet return oracle.getMarketBorrowRate(_reserve); } return reserve.currentStableBorrowRate; } /** * @dev gets the reserve average stable borrow rate. The average stable rate is the weighted average * of all the loans taken at stable rate. * @param _reserve the reserve address * @return the reserve current average borrow rate **/ function getReserveCurrentAverageStableBorrowRate(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.currentAverageStableBorrowRate; } /** * @dev gets the reserve liquidity rate * @param _reserve the reserve address * @return the reserve liquidity rate **/ function getReserveCurrentLiquidityRate(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.currentLiquidityRate; } /** * @dev gets the reserve liquidity cumulative index * @param _reserve the reserve address * @return the reserve liquidity cumulative index **/ function getReserveLiquidityCumulativeIndex(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.lastLiquidityCumulativeIndex; } /** * @dev gets the reserve variable borrow index * @param _reserve the reserve address * @return the reserve variable borrow index **/ function getReserveVariableBorrowsCumulativeIndex(address _reserve) external view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.lastVariableBorrowCumulativeIndex; } /** * @dev this function aggregates the configuration parameters of the reserve. * It's used in the LendingPoolDataProvider specifically to save gas, and avoid * multiple external contract calls to fetch the same data. * @param _reserve the reserve address * @return the reserve decimals * @return the base ltv as collateral * @return the liquidation threshold * @return if the reserve is used as collateral or not **/ function getReserveConfiguration(address _reserve) external view returns (uint256, uint256, uint256, bool) { uint256 decimals; uint256 baseLTVasCollateral; uint256 liquidationThreshold; bool usageAsCollateralEnabled; CoreLibrary.ReserveData storage reserve = reserves[_reserve]; decimals = reserve.decimals; baseLTVasCollateral = reserve.baseLTVasCollateral; liquidationThreshold = reserve.liquidationThreshold; usageAsCollateralEnabled = reserve.usageAsCollateralEnabled; return (decimals, baseLTVasCollateral, liquidationThreshold, usageAsCollateralEnabled); } /** * @dev returns the decimals of the reserve * @param _reserve the reserve address * @return the reserve decimals **/ function getReserveDecimals(address _reserve) external view returns (uint256) { return reserves[_reserve].decimals; } /** * @dev returns true if the reserve is enabled for borrowing * @param _reserve the reserve address * @return true if the reserve is enabled for borrowing, false otherwise **/ function isReserveBorrowingEnabled(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.borrowingEnabled; } /** * @dev returns true if the reserve is enabled as collateral * @param _reserve the reserve address * @return true if the reserve is enabled as collateral, false otherwise **/ function isReserveUsageAsCollateralEnabled(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.usageAsCollateralEnabled; } /** * @dev returns true if the stable rate is enabled on reserve * @param _reserve the reserve address * @return true if the stable rate is enabled on reserve, false otherwise **/ function getReserveIsStableBorrowRateEnabled(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.isStableBorrowRateEnabled; } /** * @dev returns true if the reserve is active * @param _reserve the reserve address * @return true if the reserve is active, false otherwise **/ function getReserveIsActive(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.isActive; } /** * @notice returns if a reserve is freezed * @param _reserve the reserve for which the information is needed * @return true if the reserve is freezed, false otherwise **/ function getReserveIsFreezed(address _reserve) external view returns (bool) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; return reserve.isFreezed; } /** * @notice returns the timestamp of the last action on the reserve * @param _reserve the reserve for which the information is needed * @return the last updated timestamp of the reserve **/ function getReserveLastUpdate(address _reserve) external view returns (uint40 timestamp) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; timestamp = reserve.lastUpdateTimestamp; } /** * @dev returns the utilization rate U of a specific reserve * @param _reserve the reserve for which the information is needed * @return the utilization rate in ray **/ function getReserveUtilizationRate(address _reserve) public view returns (uint256) { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; uint256 totalBorrows = reserve.getTotalBorrows(); if (totalBorrows == 0) { return 0; } uint256 availableLiquidity = getReserveAvailableLiquidity(_reserve); return totalBorrows.rayDiv(availableLiquidity.add(totalBorrows)); } /** * @return the array of reserves configured on the core **/ function getReserves() external view returns (address[] memory) { return reservesList; } /** * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return true if the user has chosen to use the reserve as collateral, false otherwise **/ function isUserUseReserveAsCollateralEnabled(address _reserve, address _user) external view returns (bool) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; return user.useAsCollateral; } /** * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the origination fee for the user **/ function getUserOriginationFee(address _reserve, address _user) external view returns (uint256) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; return user.originationFee; } /** * @dev users with no loans in progress have NONE as borrow rate mode * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the borrow rate mode for the user, **/ function getUserCurrentBorrowRateMode(address _reserve, address _user) public view returns (CoreLibrary.InterestRateMode) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; if (user.principalBorrowBalance == 0) { return CoreLibrary.InterestRateMode.NONE; } return user.stableBorrowRate > 0 ? CoreLibrary.InterestRateMode.STABLE : CoreLibrary.InterestRateMode.VARIABLE; } /** * @dev gets the current borrow rate of the user * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the borrow rate for the user, **/ function getUserCurrentBorrowRate(address _reserve, address _user) internal view returns (uint256) { CoreLibrary.InterestRateMode rateMode = getUserCurrentBorrowRateMode(_reserve, _user); if (rateMode == CoreLibrary.InterestRateMode.NONE) { return 0; } return rateMode == CoreLibrary.InterestRateMode.STABLE ? usersReserveData[_user][_reserve].stableBorrowRate : reserves[_reserve].currentVariableBorrowRate; } /** * @dev the stable rate returned is 0 if the user is borrowing at variable or not borrowing at all * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the user stable rate **/ function getUserCurrentStableBorrowRate(address _reserve, address _user) external view returns (uint256) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; return user.stableBorrowRate; } /** * @dev calculates and returns the borrow balances of the user * @param _reserve the address of the reserve * @param _user the address of the user * @return the principal borrow balance, the compounded balance and the balance increase since the last borrow/repay/swap/rebalance **/ function getUserBorrowBalances(address _reserve, address _user) public view returns (uint256, uint256, uint256) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; if (user.principalBorrowBalance == 0) { return (0, 0, 0); } uint256 principal = user.principalBorrowBalance; uint256 compoundedBalance = CoreLibrary.getCompoundedBorrowBalance( user, reserves[_reserve] ); return (principal, compoundedBalance, compoundedBalance.sub(principal)); } /** * @dev the variable borrow index of the user is 0 if the user is not borrowing or borrowing at stable * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the variable borrow index for the user **/ function getUserVariableBorrowCumulativeIndex(address _reserve, address _user) external view returns (uint256) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; return user.lastVariableBorrowCumulativeIndex; } /** * @dev the variable borrow index of the user is 0 if the user is not borrowing or borrowing at stable * @param _reserve the address of the reserve for which the information is needed * @param _user the address of the user for which the information is needed * @return the variable borrow index for the user **/ function getUserLastUpdate(address _reserve, address _user) external view returns (uint256 timestamp) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; timestamp = user.lastUpdateTimestamp; } /** * @dev updates the lending pool core configuration **/ function refreshConfiguration() external onlyLendingPoolConfigurator { refreshConfigInternal(); } /** * @dev initializes a reserve * @param _reserve the address of the reserve * @param _aTokenAddress the address of the overlying aToken contract * @param _decimals the decimals of the reserve currency * @param _interestRateStrategyAddress the address of the interest rate strategy contract **/ function initReserve( address _reserve, address _aTokenAddress, uint256 _decimals, address _interestRateStrategyAddress ) external onlyLendingPoolConfigurator { reserves[_reserve].init(_aTokenAddress, _decimals, _interestRateStrategyAddress); addReserveToListInternal(_reserve); } /** * @dev removes the last added reserve in the reservesList array * @param _reserveToRemove the address of the reserve **/ function removeLastAddedReserve(address _reserveToRemove) external onlyLendingPoolConfigurator { address lastReserve = reservesList[reservesList.length-1]; require(lastReserve == _reserveToRemove, "Reserve being removed is different than the reserve requested"); //as we can't check if totalLiquidity is 0 (since the reserve added might not be an ERC20) we at least check that there is nothing borrowed require(getReserveTotalBorrows(lastReserve) == 0, "Cannot remove a reserve with liquidity deposited"); reserves[lastReserve].isActive = false; reserves[lastReserve].aTokenAddress = address(0); reserves[lastReserve].decimals = 0; reserves[lastReserve].lastLiquidityCumulativeIndex = 0; reserves[lastReserve].lastVariableBorrowCumulativeIndex = 0; reserves[lastReserve].borrowingEnabled = false; reserves[lastReserve].usageAsCollateralEnabled = false; reserves[lastReserve].baseLTVasCollateral = 0; reserves[lastReserve].liquidationThreshold = 0; reserves[lastReserve].liquidationBonus = 0; reserves[lastReserve].interestRateStrategyAddress = address(0); reservesList.pop(); } /** * @dev updates the address of the interest rate strategy contract * @param _reserve the address of the reserve * @param _rateStrategyAddress the address of the interest rate strategy contract **/ function setReserveInterestRateStrategyAddress(address _reserve, address _rateStrategyAddress) external onlyLendingPoolConfigurator { reserves[_reserve].interestRateStrategyAddress = _rateStrategyAddress; } /** * @dev enables borrowing on a reserve. Also sets the stable rate borrowing * @param _reserve the address of the reserve * @param _stableBorrowRateEnabled true if the stable rate needs to be enabled, false otherwise **/ function enableBorrowingOnReserve(address _reserve, bool _stableBorrowRateEnabled) external onlyLendingPoolConfigurator { reserves[_reserve].enableBorrowing(_stableBorrowRateEnabled); } /** * @dev disables borrowing on a reserve * @param _reserve the address of the reserve **/ function disableBorrowingOnReserve(address _reserve) external onlyLendingPoolConfigurator { reserves[_reserve].disableBorrowing(); } /** * @dev enables a reserve to be used as collateral * @param _reserve the address of the reserve **/ function enableReserveAsCollateral( address _reserve, uint256 _baseLTVasCollateral, uint256 _liquidationThreshold, uint256 _liquidationBonus ) external onlyLendingPoolConfigurator { reserves[_reserve].enableAsCollateral( _baseLTVasCollateral, _liquidationThreshold, _liquidationBonus ); } /** * @dev disables a reserve to be used as collateral * @param _reserve the address of the reserve **/ function disableReserveAsCollateral(address _reserve) external onlyLendingPoolConfigurator { reserves[_reserve].disableAsCollateral(); } /** * @dev enable the stable borrow rate mode on a reserve * @param _reserve the address of the reserve **/ function enableReserveStableBorrowRate(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isStableBorrowRateEnabled = true; } /** * @dev disable the stable borrow rate mode on a reserve * @param _reserve the address of the reserve **/ function disableReserveStableBorrowRate(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isStableBorrowRateEnabled = false; } /** * @dev activates a reserve * @param _reserve the address of the reserve **/ function activateReserve(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; require( reserve.lastLiquidityCumulativeIndex > 0 && reserve.lastVariableBorrowCumulativeIndex > 0, "Reserve has not been initialized yet" ); reserve.isActive = true; } /** * @dev deactivates a reserve * @param _reserve the address of the reserve **/ function deactivateReserve(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isActive = false; } /** * @notice allows the configurator to freeze the reserve. * A freezed reserve does not allow any action apart from repay, redeem, liquidationCall, rebalance. * @param _reserve the address of the reserve **/ function freezeReserve(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isFreezed = true; } /** * @notice allows the configurator to unfreeze the reserve. A unfreezed reserve allows any action to be executed. * @param _reserve the address of the reserve **/ function unfreezeReserve(address _reserve) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.isFreezed = false; } /** * @notice allows the configurator to update the loan to value of a reserve * @param _reserve the address of the reserve * @param _ltv the new loan to value **/ function setReserveBaseLTVasCollateral(address _reserve, uint256 _ltv) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.baseLTVasCollateral = _ltv; } /** * @notice allows the configurator to update the liquidation threshold of a reserve * @param _reserve the address of the reserve * @param _threshold the new liquidation threshold **/ function setReserveLiquidationThreshold(address _reserve, uint256 _threshold) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.liquidationThreshold = _threshold; } /** * @notice allows the configurator to update the liquidation bonus of a reserve * @param _reserve the address of the reserve * @param _bonus the new liquidation bonus **/ function setReserveLiquidationBonus(address _reserve, uint256 _bonus) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.liquidationBonus = _bonus; } /** * @notice allows the configurator to update the reserve decimals * @param _reserve the address of the reserve * @param _decimals the decimals of the reserve **/ function setReserveDecimals(address _reserve, uint256 _decimals) external onlyLendingPoolConfigurator { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; reserve.decimals = _decimals; } /** * @notice internal functions **/ /** * @dev updates the state of a reserve as a consequence of a borrow action. * @param _reserve the address of the reserve on which the user is borrowing * @param _user the address of the borrower * @param _principalBorrowBalance the previous borrow balance of the borrower before the action * @param _balanceIncrease the accrued interest of the user on the previous borrowed amount * @param _amountBorrowed the new amount borrowed * @param _rateMode the borrow rate mode (stable, variable) **/ function updateReserveStateOnBorrowInternal( address _reserve, address _user, uint256 _principalBorrowBalance, uint256 _balanceIncrease, uint256 _amountBorrowed, CoreLibrary.InterestRateMode _rateMode ) internal { reserves[_reserve].updateCumulativeIndexes(); //increasing reserve total borrows to account for the new borrow balance of the user //NOTE: Depending on the previous borrow mode, the borrows might need to be switched from variable to stable or vice versa updateReserveTotalBorrowsByRateModeInternal( _reserve, _user, _principalBorrowBalance, _balanceIncrease, _amountBorrowed, _rateMode ); } /** * @dev updates the state of a user as a consequence of a borrow action. * @param _reserve the address of the reserve on which the user is borrowing * @param _user the address of the borrower * @param _amountBorrowed the amount borrowed * @param _balanceIncrease the accrued interest of the user on the previous borrowed amount * @param _rateMode the borrow rate mode (stable, variable) * @return the final borrow rate for the user. Emitted by the borrow() event **/ function updateUserStateOnBorrowInternal( address _reserve, address _user, uint256 _amountBorrowed, uint256 _balanceIncrease, uint256 _fee, CoreLibrary.InterestRateMode _rateMode ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; if (_rateMode == CoreLibrary.InterestRateMode.STABLE) { //stable //reset the user variable index, and update the stable rate user.stableBorrowRate = reserve.currentStableBorrowRate; user.lastVariableBorrowCumulativeIndex = 0; } else if (_rateMode == CoreLibrary.InterestRateMode.VARIABLE) { //variable //reset the user stable rate, and store the new borrow index user.stableBorrowRate = 0; user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex; } else { revert("Invalid borrow rate mode"); } //increase the principal borrows and the origination fee user.principalBorrowBalance = user.principalBorrowBalance.add(_amountBorrowed).add( _balanceIncrease ); user.originationFee = user.originationFee.add(_fee); //solium-disable-next-line user.lastUpdateTimestamp = uint40(block.timestamp); } /** * @dev updates the state of the reserve as a consequence of a repay action. * @param _reserve the address of the reserve on which the user is repaying * @param _user the address of the borrower * @param _paybackAmountMinusFees the amount being paid back minus fees * @param _balanceIncrease the accrued interest on the borrowed amount **/ function updateReserveStateOnRepayInternal( address _reserve, address _user, uint256 _paybackAmountMinusFees, uint256 _balanceIncrease ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; CoreLibrary.InterestRateMode borrowRateMode = getUserCurrentBorrowRateMode(_reserve, _user); //update the indexes reserves[_reserve].updateCumulativeIndexes(); //compound the cumulated interest to the borrow balance and then subtracting the payback amount if (borrowRateMode == CoreLibrary.InterestRateMode.STABLE) { reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _balanceIncrease, user.stableBorrowRate ); reserve.decreaseTotalBorrowsStableAndUpdateAverageRate( _paybackAmountMinusFees, user.stableBorrowRate ); } else { reserve.increaseTotalBorrowsVariable(_balanceIncrease); reserve.decreaseTotalBorrowsVariable(_paybackAmountMinusFees); } } /** * @dev updates the state of the user as a consequence of a repay action. * @param _reserve the address of the reserve on which the user is repaying * @param _user the address of the borrower * @param _paybackAmountMinusFees the amount being paid back minus fees * @param _originationFeeRepaid the fee on the amount that is being repaid * @param _balanceIncrease the accrued interest on the borrowed amount * @param _repaidWholeLoan true if the user is repaying the whole loan **/ function updateUserStateOnRepayInternal( address _reserve, address _user, uint256 _paybackAmountMinusFees, uint256 _originationFeeRepaid, uint256 _balanceIncrease, bool _repaidWholeLoan ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; //update the user principal borrow balance, adding the cumulated interest and then subtracting the payback amount user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease).sub( _paybackAmountMinusFees ); user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex; //if the balance decrease is equal to the previous principal (user is repaying the whole loan) //and the rate mode is stable, we reset the interest rate mode of the user if (_repaidWholeLoan) { user.stableBorrowRate = 0; user.lastVariableBorrowCumulativeIndex = 0; } user.originationFee = user.originationFee.sub(_originationFeeRepaid); //solium-disable-next-line user.lastUpdateTimestamp = uint40(block.timestamp); } /** * @dev updates the state of the user as a consequence of a swap rate action. * @param _reserve the address of the reserve on which the user is performing the rate swap * @param _user the address of the borrower * @param _principalBorrowBalance the the principal amount borrowed by the user * @param _compoundedBorrowBalance the principal amount plus the accrued interest * @param _currentRateMode the rate mode at which the user borrowed **/ function updateReserveStateOnSwapRateInternal( address _reserve, address _user, uint256 _principalBorrowBalance, uint256 _compoundedBorrowBalance, CoreLibrary.InterestRateMode _currentRateMode ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; //compounding reserve indexes reserve.updateCumulativeIndexes(); if (_currentRateMode == CoreLibrary.InterestRateMode.STABLE) { uint256 userCurrentStableRate = user.stableBorrowRate; //swap to variable reserve.decreaseTotalBorrowsStableAndUpdateAverageRate( _principalBorrowBalance, userCurrentStableRate ); //decreasing stable from old principal balance reserve.increaseTotalBorrowsVariable(_compoundedBorrowBalance); //increase variable borrows } else if (_currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) { //swap to stable uint256 currentStableRate = reserve.currentStableBorrowRate; reserve.decreaseTotalBorrowsVariable(_principalBorrowBalance); reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _compoundedBorrowBalance, currentStableRate ); } else { revert("Invalid rate mode received"); } } /** * @dev updates the state of the user as a consequence of a swap rate action. * @param _reserve the address of the reserve on which the user is performing the swap * @param _user the address of the borrower * @param _balanceIncrease the accrued interest on the borrowed amount * @param _currentRateMode the current rate mode of the user **/ function updateUserStateOnSwapRateInternal( address _reserve, address _user, uint256 _balanceIncrease, CoreLibrary.InterestRateMode _currentRateMode ) internal returns (CoreLibrary.InterestRateMode) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.InterestRateMode newMode = CoreLibrary.InterestRateMode.NONE; if (_currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) { //switch to stable newMode = CoreLibrary.InterestRateMode.STABLE; user.stableBorrowRate = reserve.currentStableBorrowRate; user.lastVariableBorrowCumulativeIndex = 0; } else if (_currentRateMode == CoreLibrary.InterestRateMode.STABLE) { newMode = CoreLibrary.InterestRateMode.VARIABLE; user.stableBorrowRate = 0; user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex; } else { revert("Invalid interest rate mode received"); } //compounding cumulated interest user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease); //solium-disable-next-line user.lastUpdateTimestamp = uint40(block.timestamp); return newMode; } /** * @dev updates the state of the principal reserve as a consequence of a liquidation action. * @param _principalReserve the address of the principal reserve that is being repaid * @param _user the address of the borrower * @param _amountToLiquidate the amount being repaid by the liquidator * @param _balanceIncrease the accrued interest on the borrowed amount **/ function updatePrincipalReserveStateOnLiquidationInternal( address _principalReserve, address _user, uint256 _amountToLiquidate, uint256 _balanceIncrease ) internal { CoreLibrary.ReserveData storage reserve = reserves[_principalReserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_principalReserve]; //update principal reserve data reserve.updateCumulativeIndexes(); CoreLibrary.InterestRateMode borrowRateMode = getUserCurrentBorrowRateMode( _principalReserve, _user ); if (borrowRateMode == CoreLibrary.InterestRateMode.STABLE) { //increase the total borrows by the compounded interest reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _balanceIncrease, user.stableBorrowRate ); //decrease by the actual amount to liquidate reserve.decreaseTotalBorrowsStableAndUpdateAverageRate( _amountToLiquidate, user.stableBorrowRate ); } else { //increase the total borrows by the compounded interest reserve.increaseTotalBorrowsVariable(_balanceIncrease); //decrease by the actual amount to liquidate reserve.decreaseTotalBorrowsVariable(_amountToLiquidate); } } /** * @dev updates the state of the collateral reserve as a consequence of a liquidation action. * @param _collateralReserve the address of the collateral reserve that is being liquidated **/ function updateCollateralReserveStateOnLiquidationInternal( address _collateralReserve ) internal { //update collateral reserve reserves[_collateralReserve].updateCumulativeIndexes(); } /** * @dev updates the state of the user being liquidated as a consequence of a liquidation action. * @param _reserve the address of the principal reserve that is being repaid * @param _user the address of the borrower * @param _amountToLiquidate the amount being repaid by the liquidator * @param _feeLiquidated the amount of origination fee being liquidated * @param _balanceIncrease the accrued interest on the borrowed amount **/ function updateUserStateOnLiquidationInternal( address _reserve, address _user, uint256 _amountToLiquidate, uint256 _feeLiquidated, uint256 _balanceIncrease ) internal { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; CoreLibrary.ReserveData storage reserve = reserves[_reserve]; //first increase by the compounded interest, then decrease by the liquidated amount user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease).sub( _amountToLiquidate ); if ( getUserCurrentBorrowRateMode(_reserve, _user) == CoreLibrary.InterestRateMode.VARIABLE ) { user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex; } if(_feeLiquidated > 0){ user.originationFee = user.originationFee.sub(_feeLiquidated); } //solium-disable-next-line user.lastUpdateTimestamp = uint40(block.timestamp); } /** * @dev updates the state of the reserve as a consequence of a stable rate rebalance * DEPRECATED FOR THE V1 -> V2 migration * @param _reserve the address of the principal reserve where the user borrowed * @param _user the address of the borrower * @param _balanceIncrease the accrued interest on the borrowed amount **/ function updateReserveStateOnRebalanceInternal( address _reserve, address _user, uint256 _balanceIncrease ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; reserve.updateCumulativeIndexes(); reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _balanceIncrease, user.stableBorrowRate ); } /** * @dev updates the state of the user as a consequence of a stable rate rebalance * @param _reserve the address of the principal reserve where the user borrowed * @param _user the address of the borrower * @param _balanceIncrease the accrued interest on the borrowed amount **/ function updateUserStateOnRebalanceInternal( address _reserve, address _user, uint256 _balanceIncrease ) internal { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; CoreLibrary.ReserveData storage reserve = reserves[_reserve]; user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease); user.stableBorrowRate = reserve.currentStableBorrowRate; //solium-disable-next-line user.lastUpdateTimestamp = uint40(block.timestamp); } /** * @dev updates the state of the user as a consequence of a stable rate rebalance * @param _reserve the address of the principal reserve where the user borrowed * @param _user the address of the borrower * @param _balanceIncrease the accrued interest on the borrowed amount * @param _amountBorrowed the accrued interest on the borrowed amount **/ function updateReserveTotalBorrowsByRateModeInternal( address _reserve, address _user, uint256 _principalBalance, uint256 _balanceIncrease, uint256 _amountBorrowed, CoreLibrary.InterestRateMode _newBorrowRateMode ) internal { CoreLibrary.InterestRateMode previousRateMode = getUserCurrentBorrowRateMode( _reserve, _user ); CoreLibrary.ReserveData storage reserve = reserves[_reserve]; if (previousRateMode == CoreLibrary.InterestRateMode.STABLE) { CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; reserve.decreaseTotalBorrowsStableAndUpdateAverageRate( _principalBalance, user.stableBorrowRate ); } else if (previousRateMode == CoreLibrary.InterestRateMode.VARIABLE) { reserve.decreaseTotalBorrowsVariable(_principalBalance); } uint256 newPrincipalAmount = _principalBalance.add(_balanceIncrease).add(_amountBorrowed); if (_newBorrowRateMode == CoreLibrary.InterestRateMode.STABLE) { reserve.increaseTotalBorrowsStableAndUpdateAverageRate( newPrincipalAmount, reserve.currentStableBorrowRate ); } else if (_newBorrowRateMode == CoreLibrary.InterestRateMode.VARIABLE) { reserve.increaseTotalBorrowsVariable(newPrincipalAmount); } else { revert("Invalid new borrow rate mode"); } } /** * @dev Updates the reserve current stable borrow rate Rf, the current variable borrow rate Rv and the current liquidity rate Rl. * Also updates the lastUpdateTimestamp value. Please refer to the whitepaper for further information. * @param _reserve the address of the reserve to be updated * @param _liquidityAdded the amount of liquidity added to the protocol (deposit or repay) in the previous action * @param _liquidityTaken the amount of liquidity taken from the protocol (redeem or borrow) **/ function updateReserveInterestRatesAndTimestampInternal( address _reserve, uint256 _liquidityAdded, uint256 _liquidityTaken ) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; (uint256 newLiquidityRate, uint256 newStableRate, uint256 newVariableRate) = IReserveInterestRateStrategy( reserve .interestRateStrategyAddress ) .calculateInterestRates( _reserve, getReserveAvailableLiquidity(_reserve).add(_liquidityAdded).sub(_liquidityTaken), reserve.totalBorrowsStable, reserve.totalBorrowsVariable, reserve.currentAverageStableBorrowRate ); reserve.currentLiquidityRate = newLiquidityRate; reserve.currentStableBorrowRate = newStableRate; reserve.currentVariableBorrowRate = newVariableRate; //solium-disable-next-line reserve.lastUpdateTimestamp = uint40(block.timestamp); emit ReserveUpdated( _reserve, newLiquidityRate, newStableRate, newVariableRate, reserve.lastLiquidityCumulativeIndex, reserve.lastVariableBorrowCumulativeIndex ); } /** * @dev transfers to the protocol fees of a flashloan to the fees collection address * @param _token the address of the token being transferred * @param _amount the amount being transferred **/ function transferFlashLoanProtocolFeeInternal(address _token, uint256 _amount) internal { address payable receiver = address(uint160(addressesProvider.getTokenDistributor())); if (_token != EthAddressLib.ethAddress()) { ERC20(_token).safeTransfer(receiver, _amount); } else { //solium-disable-next-line (bool result, ) = receiver.call.value(_amount)(""); require(result, "Transfer to token distributor failed"); } } /** * @dev updates the internal configuration of the core **/ function refreshConfigInternal() internal { lendingPoolAddress = addressesProvider.getLendingPool(); } /** * @dev adds a reserve to the array of the reserves address **/ function addReserveToListInternal(address _reserve) internal { bool reserveAlreadyAdded = false; for (uint256 i = 0; i < reservesList.length; i++) if (reservesList[i] == _reserve) { reserveAlreadyAdded = true; } if (!reserveAlreadyAdded) reservesList.push(_reserve); } }
LTV is calculated in percentage
.div(_userCurrentLtv);
2,063,791
[ 1, 12050, 58, 353, 8894, 316, 11622, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 263, 2892, 24899, 1355, 3935, 48, 24161, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-07-06 */ // SPDX-License-Identifier: MIXED // File @boringcrypto/boring-solidity/contracts/libraries/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64. library BoringMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } // File @boringcrypto/boring-solidity/contracts/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; // Audit on 5-Jan-2021 by Keno and BoringCrypto // Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol // Edited by BoringCrypto contract BoringOwnableData { address public owner; address public pendingOwner; } contract BoringOwnable is BoringOwnableData { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice `owner` defaults to msg.sender on construction. constructor() public { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. /// Can only be invoked by the current `owner`. /// @param newOwner Address of the new owner. /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`. /// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise. function transferOwnership( address newOwner, bool direct, bool renounce ) public onlyOwner { if (direct) { // Checks require(newOwner != address(0) || renounce, "Ownable: zero address"); // Effects emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = address(0); } else { // Effects pendingOwner = newOwner; } } /// @notice Needs to be called by `pendingOwner` to claim ownership. function claimOwnership() public { address _pendingOwner = pendingOwner; // Checks require(msg.sender == _pendingOwner, "Ownable: caller != pending owner"); // Effects emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } /// @notice Only allows the `owner` to execute the function. modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } } // File @boringcrypto/boring-solidity/contracts/interfaces/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /// @notice EIP 2612 function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // File @boringcrypto/boring-solidity/contracts/[email protected] // License-Identifier: MIT // Based on code and smartness by Ross Campbell and Keno // Uses immutable to store the domain separator to reduce gas usage // If the chain id changes due to a fork, the forked chain will calculate on the fly. pragma solidity 0.6.12; // solhint-disable no-inline-assembly contract Domain { bytes32 private constant DOMAIN_SEPARATOR_SIGNATURE_HASH = keccak256("EIP712Domain(uint256 chainId,address verifyingContract)"); // See https://eips.ethereum.org/EIPS/eip-191 string private constant EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA = "\x19\x01"; // solhint-disable var-name-mixedcase bytes32 private immutable _DOMAIN_SEPARATOR; uint256 private immutable DOMAIN_SEPARATOR_CHAIN_ID; /// @dev Calculate the DOMAIN_SEPARATOR function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) { return keccak256( abi.encode( DOMAIN_SEPARATOR_SIGNATURE_HASH, chainId, address(this) ) ); } constructor() public { uint256 chainId; assembly {chainId := chainid()} _DOMAIN_SEPARATOR = _calculateDomainSeparator(DOMAIN_SEPARATOR_CHAIN_ID = chainId); } /// @dev Return the DOMAIN_SEPARATOR // It's named internal to allow making it public from the contract that uses it by creating a simple view function // with the desired public name, such as DOMAIN_SEPARATOR or domainSeparator. // solhint-disable-next-line func-name-mixedcase function _domainSeparator() internal view returns (bytes32) { uint256 chainId; assembly {chainId := chainid()} return chainId == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId); } function _getDigest(bytes32 dataHash) internal view returns (bytes32 digest) { digest = keccak256( abi.encodePacked( EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA, _domainSeparator(), dataHash ) ); } } // File @boringcrypto/boring-solidity/contracts/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; // solhint-disable no-inline-assembly // solhint-disable not-rely-on-time // Data part taken out for building of contracts that receive delegate calls contract ERC20Data { /// @notice owner > balance mapping. mapping(address => uint256) public balanceOf; /// @notice owner > spender > allowance mapping. mapping(address => mapping(address => uint256)) public allowance; /// @notice owner > nonce mapping. Used in `permit`. mapping(address => uint256) public nonces; } abstract contract ERC20 is IERC20, Domain { /// @notice owner > balance mapping. mapping(address => uint256) public override balanceOf; /// @notice owner > spender > allowance mapping. mapping(address => mapping(address => uint256)) public override allowance; /// @notice owner > nonce mapping. Used in `permit`. mapping(address => uint256) public nonces; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /// @notice Transfers `amount` tokens from `msg.sender` to `to`. /// @param to The address to move the tokens. /// @param amount of the tokens to move. /// @return (bool) Returns True if succeeded. function transfer(address to, uint256 amount) public returns (bool) { // If `amount` is 0, or `msg.sender` is `to` nothing happens if (amount != 0 || msg.sender == to) { uint256 srcBalance = balanceOf[msg.sender]; require(srcBalance >= amount, "ERC20: balance too low"); if (msg.sender != to) { require(to != address(0), "ERC20: no zero address"); // Moved down so low balance calls safe some gas balanceOf[msg.sender] = srcBalance - amount; // Underflow is checked balanceOf[to] += amount; } } emit Transfer(msg.sender, to, amount); return true; } /// @notice Transfers `amount` tokens from `from` to `to`. Caller needs approval for `from`. /// @param from Address to draw tokens from. /// @param to The address to move the tokens. /// @param amount The token amount to move. /// @return (bool) Returns True if succeeded. function transferFrom( address from, address to, uint256 amount ) public returns (bool) { // If `amount` is 0, or `from` is `to` nothing happens if (amount != 0) { uint256 srcBalance = balanceOf[from]; require(srcBalance >= amount, "ERC20: balance too low"); if (from != to) { uint256 spenderAllowance = allowance[from][msg.sender]; // If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20). if (spenderAllowance != type(uint256).max) { require(spenderAllowance >= amount, "ERC20: allowance too low"); allowance[from][msg.sender] = spenderAllowance - amount; // Underflow is checked } require(to != address(0), "ERC20: no zero address"); // Moved down so other failed calls safe some gas balanceOf[from] = srcBalance - amount; // Underflow is checked balanceOf[to] += amount; } } emit Transfer(from, to, amount); return true; } /// @notice Approves `amount` from sender to be spend by `spender`. /// @param spender Address of the party that can draw from msg.sender's account. /// @param amount The maximum collective amount that `spender` can draw. /// @return (bool) Returns True if approved. function approve(address spender, uint256 amount) public override returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32) { return _domainSeparator(); } // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /// @notice Approves `value` from `owner_` to be spend by `spender`. /// @param owner_ Address of the owner. /// @param spender The address of the spender that gets approved to draw from `owner_`. /// @param value The maximum collective amount that `spender` can draw. /// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds). function permit( address owner_, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(owner_ != address(0), "ERC20: Owner cannot be 0"); require(block.timestamp < deadline, "ERC20: Expired"); require( ecrecover(_getDigest(keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))), v, r, s) == owner_, "ERC20: Invalid Signature" ); allowance[owner_][spender] = value; emit Approval(owner_, spender, value); } } contract ERC20WithSupply is IERC20, ERC20 { uint256 public override totalSupply; function _mint(address user, uint256 amount) private { uint256 newTotalSupply = totalSupply + amount; require(newTotalSupply >= totalSupply, "Mint overflow"); totalSupply = newTotalSupply; balanceOf[user] += amount; } function _burn(address user, uint256 amount) private { require(balanceOf[user] >= amount, "Burn too much"); totalSupply -= amount; balanceOf[user] -= amount; } } // File @boringcrypto/boring-solidity/contracts/interfaces/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; interface IMasterContract { /// @notice Init function that gets called from `BoringFactory.deploy`. /// Also kown as the constructor for cloned contracts. /// Any ETH send to `BoringFactory.deploy` ends up here. /// @param data Can be abi encoded arguments or anything else. function init(bytes calldata data) external payable; } // File @boringcrypto/boring-solidity/contracts/libraries/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; struct Rebase { uint128 elastic; uint128 base; } /// @notice A rebasing library using overflow-/underflow-safe math. library RebaseLibrary { using BoringMath for uint256; using BoringMath128 for uint128; /// @notice Calculates the base value in relationship to `elastic` and `total`. function toBase( Rebase memory total, uint256 elastic, bool roundUp ) internal pure returns (uint256 base) { if (total.elastic == 0) { base = elastic; } else { base = elastic.mul(total.base) / total.elastic; if (roundUp && base.mul(total.elastic) / total.base < elastic) { base = base.add(1); } } } /// @notice Calculates the elastic value in relationship to `base` and `total`. function toElastic( Rebase memory total, uint256 base, bool roundUp ) internal pure returns (uint256 elastic) { if (total.base == 0) { elastic = base; } else { elastic = base.mul(total.elastic) / total.base; if (roundUp && elastic.mul(total.base) / total.elastic < base) { elastic = elastic.add(1); } } } /// @notice Add `elastic` to `total` and doubles `total.base`. /// @return (Rebase) The new total. /// @return base in relationship to `elastic`. function add( Rebase memory total, uint256 elastic, bool roundUp ) internal pure returns (Rebase memory, uint256 base) { base = toBase(total, elastic, roundUp); total.elastic = total.elastic.add(elastic.to128()); total.base = total.base.add(base.to128()); return (total, base); } /// @notice Sub `base` from `total` and update `total.elastic`. /// @return (Rebase) The new total. /// @return elastic in relationship to `base`. function sub( Rebase memory total, uint256 base, bool roundUp ) internal pure returns (Rebase memory, uint256 elastic) { elastic = toElastic(total, base, roundUp); total.elastic = total.elastic.sub(elastic.to128()); total.base = total.base.sub(base.to128()); return (total, elastic); } /// @notice Add `elastic` and `base` to `total`. function add( Rebase memory total, uint256 elastic, uint256 base ) internal pure returns (Rebase memory) { total.elastic = total.elastic.add(elastic.to128()); total.base = total.base.add(base.to128()); return total; } /// @notice Subtract `elastic` and `base` to `total`. function sub( Rebase memory total, uint256 elastic, uint256 base ) internal pure returns (Rebase memory) { total.elastic = total.elastic.sub(elastic.to128()); total.base = total.base.sub(base.to128()); return total; } /// @notice Add `elastic` to `total` and update storage. /// @return newElastic Returns updated `elastic`. function addElastic(Rebase storage total, uint256 elastic) internal returns (uint256 newElastic) { newElastic = total.elastic = total.elastic.add(elastic.to128()); } /// @notice Subtract `elastic` from `total` and update storage. /// @return newElastic Returns updated `elastic`. function subElastic(Rebase storage total, uint256 elastic) internal returns (uint256 newElastic) { newElastic = total.elastic = total.elastic.sub(elastic.to128()); } } // File @boringcrypto/boring-solidity/contracts/libraries/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; // solhint-disable avoid-low-level-calls library BoringERC20 { bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol() bytes4 private constant SIG_NAME = 0x06fdde03; // name() bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals() bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256) bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256) function returnDataToString(bytes memory data) internal pure returns (string memory) { if (data.length >= 64) { return abi.decode(data, (string)); } else if (data.length == 32) { uint8 i = 0; while(i < 32 && data[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && data[i] != 0; i++) { bytesArray[i] = data[i]; } return string(bytesArray); } else { return "???"; } } /// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token symbol. function safeSymbol(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL)); return success ? returnDataToString(data) : "???"; } /// @notice Provides a safe ERC20.name version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token name. function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME)); return success ? returnDataToString(data) : "???"; } /// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value. /// @param token The address of the ERC-20 token contract. /// @return (uint8) Token decimals. function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } /// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed"); } /// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param from Transfer tokens from. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed"); } } // File @sushiswap/bentobox-sdk/contracts/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; interface IBatchFlashBorrower { function onBatchFlashLoan( address sender, IERC20[] calldata tokens, uint256[] calldata amounts, uint256[] calldata fees, bytes calldata data ) external; } // File @sushiswap/bentobox-sdk/contracts/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; interface IFlashBorrower { function onFlashLoan( address sender, IERC20 token, uint256 amount, uint256 fee, bytes calldata data ) external; } // File @sushiswap/bentobox-sdk/contracts/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; interface IStrategy { // Send the assets to the Strategy and call skim to invest them function skim(uint256 amount) external; // Harvest any profits made converted to the asset and pass them to the caller function harvest(uint256 balance, address sender) external returns (int256 amountAdded); // Withdraw assets. The returned amount can differ from the requested amount due to rounding. // The actualAmount should be very close to the amount. The difference should NOT be used to report a loss. That's what harvest is for. function withdraw(uint256 amount) external returns (uint256 actualAmount); // Withdraw all assets in the safest way possible. This shouldn't fail. function exit(uint256 balance) external returns (int256 amountAdded); } // File @sushiswap/bentobox-sdk/contracts/[email protected] // License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IBentoBoxV1 { event LogDeploy(address indexed masterContract, bytes data, address indexed cloneAddress); event LogDeposit(address indexed token, address indexed from, address indexed to, uint256 amount, uint256 share); event LogFlashLoan(address indexed borrower, address indexed token, uint256 amount, uint256 feeAmount, address indexed receiver); event LogRegisterProtocol(address indexed protocol); event LogSetMasterContractApproval(address indexed masterContract, address indexed user, bool approved); event LogStrategyDivest(address indexed token, uint256 amount); event LogStrategyInvest(address indexed token, uint256 amount); event LogStrategyLoss(address indexed token, uint256 amount); event LogStrategyProfit(address indexed token, uint256 amount); event LogStrategyQueued(address indexed token, address indexed strategy); event LogStrategySet(address indexed token, address indexed strategy); event LogStrategyTargetPercentage(address indexed token, uint256 targetPercentage); event LogTransfer(address indexed token, address indexed from, address indexed to, uint256 share); event LogWhiteListMasterContract(address indexed masterContract, bool approved); event LogWithdraw(address indexed token, address indexed from, address indexed to, uint256 amount, uint256 share); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function balanceOf(IERC20, address) external view returns (uint256); function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results); function batchFlashLoan(IBatchFlashBorrower borrower, address[] calldata receivers, IERC20[] calldata tokens, uint256[] calldata amounts, bytes calldata data) external; function claimOwnership() external; function deploy(address masterContract, bytes calldata data, bool useCreate2) external payable; function deposit(IERC20 token_, address from, address to, uint256 amount, uint256 share) external payable returns (uint256 amountOut, uint256 shareOut); function flashLoan(IFlashBorrower borrower, address receiver, IERC20 token, uint256 amount, bytes calldata data) external; function harvest(IERC20 token, bool balance, uint256 maxChangeAmount) external; function masterContractApproved(address, address) external view returns (bool); function masterContractOf(address) external view returns (address); function nonces(address) external view returns (uint256); function owner() external view returns (address); function pendingOwner() external view returns (address); function pendingStrategy(IERC20) external view returns (IStrategy); function permitToken(IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function registerProtocol() external; function setMasterContractApproval(address user, address masterContract, bool approved, uint8 v, bytes32 r, bytes32 s) external; function setStrategy(IERC20 token, IStrategy newStrategy) external; function setStrategyTargetPercentage(IERC20 token, uint64 targetPercentage_) external; function strategy(IERC20) external view returns (IStrategy); function strategyData(IERC20) external view returns (uint64 strategyStartDate, uint64 targetPercentage, uint128 balance); function toAmount(IERC20 token, uint256 share, bool roundUp) external view returns (uint256 amount); function toShare(IERC20 token, uint256 amount, bool roundUp) external view returns (uint256 share); function totals(IERC20) external view returns (Rebase memory totals_); function transfer(IERC20 token, address from, address to, uint256 share) external; function transferMultiple(IERC20 token, address from, address[] calldata tos, uint256[] calldata shares) external; function transferOwnership(address newOwner, bool direct, bool renounce) external; function whitelistMasterContract(address masterContract, bool approved) external; function whitelistedMasterContracts(address) external view returns (bool); function withdraw(IERC20 token_, address from, address to, uint256 amount, uint256 share) external returns (uint256 amountOut, uint256 shareOut); } // File contracts/MagicInternetMoney.sol // License-Identifier: MIT // Magic Internet Money // ███╗ ███╗██╗███╗ ███╗ // ████╗ ████║██║████╗ ████║ // ██╔████╔██║██║██╔████╔██║ // ██║╚██╔╝██║██║██║╚██╔╝██║ // ██║ ╚═╝ ██║██║██║ ╚═╝ ██║ // ╚═╝ ╚═╝╚═╝╚═╝ ╚═╝ // BoringCrypto, 0xMerlin pragma solidity 0.6.12; /// @title Cauldron /// @dev This contract allows contract calls to any contract (except BentoBox) /// from arbitrary callers thus, don't trust calls from this contract in any circumstances. contract MagicInternetMoney is ERC20, BoringOwnable { using BoringMath for uint256; // ERC20 'variables' string public constant symbol = "MIM"; string public constant name = "Magic Internet Money"; uint8 public constant decimals = 18; uint256 public override totalSupply; struct Minting { uint128 time; uint128 amount; } Minting public lastMint; uint256 private constant MINTING_PERIOD = 24 hours; uint256 private constant MINTING_INCREASE = 15000; uint256 private constant MINTING_PRECISION = 1e5; function mint(address to, uint256 amount) public onlyOwner { require(to != address(0), "MIM: no mint to zero address"); // Limits the amount minted per period to a convergence function, with the period duration restarting on every mint uint256 totalMintedAmount = uint256(lastMint.time < block.timestamp - MINTING_PERIOD ? 0 : lastMint.amount).add(amount); require(totalSupply == 0 || totalSupply.mul(MINTING_INCREASE) / MINTING_PRECISION >= totalMintedAmount); lastMint.time = block.timestamp.to128(); lastMint.amount = totalMintedAmount.to128(); totalSupply = totalSupply + amount; balanceOf[to] += amount; emit Transfer(address(0), to, amount); } function mintToBentoBox(address clone, uint256 amount, IBentoBoxV1 bentoBox) public onlyOwner { mint(address(bentoBox), amount); bentoBox.deposit(IERC20(address(this)), address(bentoBox), clone, amount, 0); } function burn(uint256 amount) public { require(amount <= balanceOf[msg.sender], "MIM: not enough"); balanceOf[msg.sender] -= amount; totalSupply -= amount; emit Transfer(msg.sender, address(0), amount); } } // File contracts/interfaces/IOracle.sol // License-Identifier: MIT pragma solidity 0.6.12; interface IOracle { /// @notice Get the latest exchange rate. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return success if no valid (recent) rate is available, return false else true. /// @return rate The rate of the requested asset / pair / pool. function get(bytes calldata data) external returns (bool success, uint256 rate); /// @notice Check the last exchange rate without any state changes. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return success if no valid (recent) rate is available, return false else true. /// @return rate The rate of the requested asset / pair / pool. function peek(bytes calldata data) external view returns (bool success, uint256 rate); /// @notice Check the current spot exchange rate without any state changes. For oracles like TWAP this will be different from peek(). /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return rate The rate of the requested asset / pair / pool. function peekSpot(bytes calldata data) external view returns (uint256 rate); /// @notice Returns a human readable (short) name about this oracle. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return (string) A human readable symbol name about this oracle. function symbol(bytes calldata data) external view returns (string memory); /// @notice Returns a human readable name about this oracle. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return (string) A human readable name about this oracle. function name(bytes calldata data) external view returns (string memory); } // File contracts/interfaces/ISwapper.sol // License-Identifier: MIT pragma solidity 0.6.12; interface ISwapper { /// @notice Withdraws 'amountFrom' of token 'from' from the BentoBox account for this swapper. /// Swaps it for at least 'amountToMin' of token 'to'. /// Transfers the swapped tokens of 'to' into the BentoBox using a plain ERC20 transfer. /// Returns the amount of tokens 'to' transferred to BentoBox. /// (The BentoBox skim function will be used by the caller to get the swapped funds). function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) external returns (uint256 extraShare, uint256 shareReturned); /// @notice Calculates the amount of token 'from' needed to complete the swap (amountFrom), /// this should be less than or equal to amountFromMax. /// Withdraws 'amountFrom' of token 'from' from the BentoBox account for this swapper. /// Swaps it for exactly 'exactAmountTo' of token 'to'. /// Transfers the swapped tokens of 'to' into the BentoBox using a plain ERC20 transfer. /// Transfers allocated, but unused 'from' tokens within the BentoBox to 'refundTo' (amountFromMax - amountFrom). /// Returns the amount of 'from' tokens withdrawn from BentoBox (amountFrom). /// (The BentoBox skim function will be used by the caller to get the swapped funds). function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) external returns (uint256 shareUsed, uint256 shareReturned); } // File contracts/CauldronV2.sol // License-Identifier: UNLICENSED // Cauldron // ( ( ( // )\ ) ( )\ )\ ) ( // (((_) ( /( ))\ ((_)(()/( )( ( ( // )\___ )(_)) /((_) _ ((_))(()\ )\ )\ ) // ((/ __|((_)_ (_))( | | _| | ((_) ((_) _(_/( // | (__ / _` || || || |/ _` | | '_|/ _ \| ' \)) // \___|\__,_| \_,_||_|\__,_| |_| \___/|_||_| // Copyright (c) 2021 BoringCrypto - All rights reserved // Twitter: @Boring_Crypto // Special thanks to: // @0xKeno - for all his invaluable contributions // @burger_crypto - for the idea of trying to let the LPs benefit from liquidations pragma solidity 0.6.12; // solhint-disable avoid-low-level-calls // solhint-disable no-inline-assembly /// @title Cauldron /// @dev This contract allows contract calls to any contract (except BentoBox) /// from arbitrary callers thus, don't trust calls from this contract in any circumstances. contract CauldronV2Flat is BoringOwnable, IMasterContract { using BoringMath for uint256; using BoringMath128 for uint128; using RebaseLibrary for Rebase; using BoringERC20 for IERC20; event LogExchangeRate(uint256 rate); event LogAccrue(uint128 accruedAmount); event LogAddCollateral(address indexed from, address indexed to, uint256 share); event LogRemoveCollateral(address indexed from, address indexed to, uint256 share); event LogBorrow(address indexed from, address indexed to, uint256 amount, uint256 part); event LogRepay(address indexed from, address indexed to, uint256 amount, uint256 part); event LogFeeTo(address indexed newFeeTo); event LogWithdrawFees(address indexed feeTo, uint256 feesEarnedFraction); // Immutables (for MasterContract and all clones) IBentoBoxV1 public immutable bentoBox; CauldronV2Flat public immutable masterContract; IERC20 public immutable magicInternetMoney; // MasterContract variables address public feeTo; // Per clone variables // Clone init settings IERC20 public collateral; IOracle public oracle; bytes public oracleData; // Total amounts uint256 public totalCollateralShare; // Total collateral supplied Rebase public totalBorrow; // elastic = Total token amount to be repayed by borrowers, base = Total parts of the debt held by borrowers // User balances mapping(address => uint256) public userCollateralShare; mapping(address => uint256) public userBorrowPart; /// @notice Exchange and interest rate tracking. /// This is 'cached' here because calls to Oracles can be very expensive. uint256 public exchangeRate; struct AccrueInfo { uint64 lastAccrued; uint128 feesEarned; uint64 INTEREST_PER_SECOND; } AccrueInfo public accrueInfo; // Settings uint256 public COLLATERIZATION_RATE; uint256 private constant COLLATERIZATION_RATE_PRECISION = 1e5; // Must be less than EXCHANGE_RATE_PRECISION (due to optimization in math) uint256 private constant EXCHANGE_RATE_PRECISION = 1e18; uint256 public LIQUIDATION_MULTIPLIER; uint256 private constant LIQUIDATION_MULTIPLIER_PRECISION = 1e5; uint256 public BORROW_OPENING_FEE; uint256 private constant BORROW_OPENING_FEE_PRECISION = 1e5; uint256 private constant DISTRIBUTION_PART = 10; uint256 private constant DISTRIBUTION_PRECISION = 100; /// @notice The constructor is only used for the initial master contract. Subsequent clones are initialised via `init`. constructor(IBentoBoxV1 bentoBox_, IERC20 magicInternetMoney_) public { bentoBox = bentoBox_; magicInternetMoney = magicInternetMoney_; masterContract = this; } /// @notice Serves as the constructor for clones, as clones can't have a regular constructor /// @dev `data` is abi encoded in the format: (IERC20 collateral, IERC20 asset, IOracle oracle, bytes oracleData) function init(bytes calldata data) public payable override { require(address(collateral) == address(0), "Cauldron: already initialized"); (collateral, oracle, oracleData, accrueInfo.INTEREST_PER_SECOND, LIQUIDATION_MULTIPLIER, COLLATERIZATION_RATE, BORROW_OPENING_FEE) = abi.decode(data, (IERC20, IOracle, bytes, uint64, uint256, uint256, uint256)); require(address(collateral) != address(0), "Cauldron: bad pair"); } /// @notice Accrues the interest on the borrowed tokens and handles the accumulation of fees. function accrue() public { AccrueInfo memory _accrueInfo = accrueInfo; // Number of seconds since accrue was called uint256 elapsedTime = block.timestamp - _accrueInfo.lastAccrued; if (elapsedTime == 0) { return; } _accrueInfo.lastAccrued = uint64(block.timestamp); Rebase memory _totalBorrow = totalBorrow; if (_totalBorrow.base == 0) { accrueInfo = _accrueInfo; return; } // Accrue interest uint128 extraAmount = (uint256(_totalBorrow.elastic).mul(_accrueInfo.INTEREST_PER_SECOND).mul(elapsedTime) / 1e18).to128(); _totalBorrow.elastic = _totalBorrow.elastic.add(extraAmount); _accrueInfo.feesEarned = _accrueInfo.feesEarned.add(extraAmount); totalBorrow = _totalBorrow; accrueInfo = _accrueInfo; emit LogAccrue(extraAmount); } /// @notice Concrete implementation of `isSolvent`. Includes a third parameter to allow caching `exchangeRate`. /// @param _exchangeRate The exchange rate. Used to cache the `exchangeRate` between calls. function _isSolvent(address user, uint256 _exchangeRate) internal view returns (bool) { // accrue must have already been called! uint256 borrowPart = userBorrowPart[user]; if (borrowPart == 0) return true; uint256 collateralShare = userCollateralShare[user]; if (collateralShare == 0) return false; Rebase memory _totalBorrow = totalBorrow; return bentoBox.toAmount( collateral, collateralShare.mul(EXCHANGE_RATE_PRECISION / COLLATERIZATION_RATE_PRECISION).mul(COLLATERIZATION_RATE), false ) >= // Moved exchangeRate here instead of dividing the other side to preserve more precision borrowPart.mul(_totalBorrow.elastic).mul(_exchangeRate) / _totalBorrow.base; } /// @dev Checks if the user is solvent in the closed liquidation case at the end of the function body. modifier solvent() { _; require(_isSolvent(msg.sender, exchangeRate), "Cauldron: user insolvent"); } /// @notice Gets the exchange rate. I.e how much collateral to buy 1e18 asset. /// This function is supposed to be invoked if needed because Oracle queries can be expensive. /// @return updated True if `exchangeRate` was updated. /// @return rate The new exchange rate. function updateExchangeRate() public returns (bool updated, uint256 rate) { (updated, rate) = oracle.get(oracleData); if (updated) { exchangeRate = rate; emit LogExchangeRate(rate); } else { // Return the old rate if fetching wasn't successful rate = exchangeRate; } } /// @dev Helper function to move tokens. /// @param token The ERC-20 token. /// @param share The amount in shares to add. /// @param total Grand total amount to deduct from this contract's balance. Only applicable if `skim` is True. /// Only used for accounting checks. /// @param skim If True, only does a balance check on this contract. /// False if tokens from msg.sender in `bentoBox` should be transferred. function _addTokens( IERC20 token, uint256 share, uint256 total, bool skim ) internal { if (skim) { require(share <= bentoBox.balanceOf(token, address(this)).sub(total), "Cauldron: Skim too much"); } else { bentoBox.transfer(token, msg.sender, address(this), share); } } /// @notice Adds `collateral` from msg.sender to the account `to`. /// @param to The receiver of the tokens. /// @param skim True if the amount should be skimmed from the deposit balance of msg.sender.x /// False if tokens from msg.sender in `bentoBox` should be transferred. /// @param share The amount of shares to add for `to`. function addCollateral( address to, bool skim, uint256 share ) public { userCollateralShare[to] = userCollateralShare[to].add(share); uint256 oldTotalCollateralShare = totalCollateralShare; totalCollateralShare = oldTotalCollateralShare.add(share); _addTokens(collateral, share, oldTotalCollateralShare, skim); emit LogAddCollateral(skim ? address(bentoBox) : msg.sender, to, share); } /// @dev Concrete implementation of `removeCollateral`. function _removeCollateral(address to, uint256 share) internal { userCollateralShare[msg.sender] = userCollateralShare[msg.sender].sub(share); totalCollateralShare = totalCollateralShare.sub(share); emit LogRemoveCollateral(msg.sender, to, share); bentoBox.transfer(collateral, address(this), to, share); } /// @notice Removes `share` amount of collateral and transfers it to `to`. /// @param to The receiver of the shares. /// @param share Amount of shares to remove. function removeCollateral(address to, uint256 share) public solvent { // accrue must be called because we check solvency accrue(); _removeCollateral(to, share); } /// @dev Concrete implementation of `borrow`. function _borrow(address to, uint256 amount) internal returns (uint256 part, uint256 share) { uint256 feeAmount = amount.mul(BORROW_OPENING_FEE) / BORROW_OPENING_FEE_PRECISION; // A flat % fee is charged for any borrow (totalBorrow, part) = totalBorrow.add(amount.add(feeAmount), true); accrueInfo.feesEarned = accrueInfo.feesEarned.add(uint128(feeAmount)); userBorrowPart[msg.sender] = userBorrowPart[msg.sender].add(part); // As long as there are tokens on this contract you can 'mint'... this enables limiting borrows share = bentoBox.toShare(magicInternetMoney, amount, false); bentoBox.transfer(magicInternetMoney, address(this), to, share); emit LogBorrow(msg.sender, to, amount.add(feeAmount), part); } /// @notice Sender borrows `amount` and transfers it to `to`. /// @return part Total part of the debt held by borrowers. /// @return share Total amount in shares borrowed. function borrow(address to, uint256 amount) public solvent returns (uint256 part, uint256 share) { accrue(); (part, share) = _borrow(to, amount); } /// @dev Concrete implementation of `repay`. function _repay( address to, bool skim, uint256 part ) internal returns (uint256 amount) { (totalBorrow, amount) = totalBorrow.sub(part, true); userBorrowPart[to] = userBorrowPart[to].sub(part); uint256 share = bentoBox.toShare(magicInternetMoney, amount, true); bentoBox.transfer(magicInternetMoney, skim ? address(bentoBox) : msg.sender, address(this), share); emit LogRepay(skim ? address(bentoBox) : msg.sender, to, amount, part); } /// @notice Repays a loan. /// @param to Address of the user this payment should go. /// @param skim True if the amount should be skimmed from the deposit balance of msg.sender. /// False if tokens from msg.sender in `bentoBox` should be transferred. /// @param part The amount to repay. See `userBorrowPart`. /// @return amount The total amount repayed. function repay( address to, bool skim, uint256 part ) public returns (uint256 amount) { accrue(); amount = _repay(to, skim, part); } // Functions that need accrue to be called uint8 internal constant ACTION_REPAY = 2; uint8 internal constant ACTION_REMOVE_COLLATERAL = 4; uint8 internal constant ACTION_BORROW = 5; uint8 internal constant ACTION_GET_REPAY_SHARE = 6; uint8 internal constant ACTION_GET_REPAY_PART = 7; uint8 internal constant ACTION_ACCRUE = 8; // Functions that don't need accrue to be called uint8 internal constant ACTION_ADD_COLLATERAL = 10; uint8 internal constant ACTION_UPDATE_EXCHANGE_RATE = 11; // Function on BentoBox uint8 internal constant ACTION_BENTO_DEPOSIT = 20; uint8 internal constant ACTION_BENTO_WITHDRAW = 21; uint8 internal constant ACTION_BENTO_TRANSFER = 22; uint8 internal constant ACTION_BENTO_TRANSFER_MULTIPLE = 23; uint8 internal constant ACTION_BENTO_SETAPPROVAL = 24; // Any external call (except to BentoBox) uint8 internal constant ACTION_CALL = 30; int256 internal constant USE_VALUE1 = -1; int256 internal constant USE_VALUE2 = -2; /// @dev Helper function for choosing the correct value (`value1` or `value2`) depending on `inNum`. function _num( int256 inNum, uint256 value1, uint256 value2 ) internal pure returns (uint256 outNum) { outNum = inNum >= 0 ? uint256(inNum) : (inNum == USE_VALUE1 ? value1 : value2); } /// @dev Helper function for depositing into `bentoBox`. function _bentoDeposit( bytes memory data, uint256 value, uint256 value1, uint256 value2 ) internal returns (uint256, uint256) { (IERC20 token, address to, int256 amount, int256 share) = abi.decode(data, (IERC20, address, int256, int256)); amount = int256(_num(amount, value1, value2)); // Done this way to avoid stack too deep errors share = int256(_num(share, value1, value2)); return bentoBox.deposit{value: value}(token, msg.sender, to, uint256(amount), uint256(share)); } /// @dev Helper function to withdraw from the `bentoBox`. function _bentoWithdraw( bytes memory data, uint256 value1, uint256 value2 ) internal returns (uint256, uint256) { (IERC20 token, address to, int256 amount, int256 share) = abi.decode(data, (IERC20, address, int256, int256)); return bentoBox.withdraw(token, msg.sender, to, _num(amount, value1, value2), _num(share, value1, value2)); } /// @dev Helper function to perform a contract call and eventually extracting revert messages on failure. /// Calls to `bentoBox` are not allowed for obvious security reasons. /// This also means that calls made from this contract shall *not* be trusted. function _call( uint256 value, bytes memory data, uint256 value1, uint256 value2 ) internal returns (bytes memory, uint8) { (address callee, bytes memory callData, bool useValue1, bool useValue2, uint8 returnValues) = abi.decode(data, (address, bytes, bool, bool, uint8)); if (useValue1 && !useValue2) { callData = abi.encodePacked(callData, value1); } else if (!useValue1 && useValue2) { callData = abi.encodePacked(callData, value2); } else if (useValue1 && useValue2) { callData = abi.encodePacked(callData, value1, value2); } require(callee != address(bentoBox) && callee != address(this), "Cauldron: can't call"); (bool success, bytes memory returnData) = callee.call{value: value}(callData); require(success, "Cauldron: call failed"); return (returnData, returnValues); } struct CookStatus { bool needsSolvencyCheck; bool hasAccrued; } /// @notice Executes a set of actions and allows composability (contract calls) to other contracts. /// @param actions An array with a sequence of actions to execute (see ACTION_ declarations). /// @param values A one-to-one mapped array to `actions`. ETH amounts to send along with the actions. /// Only applicable to `ACTION_CALL`, `ACTION_BENTO_DEPOSIT`. /// @param datas A one-to-one mapped array to `actions`. Contains abi encoded data of function arguments. /// @return value1 May contain the first positioned return value of the last executed action (if applicable). /// @return value2 May contain the second positioned return value of the last executed action which returns 2 values (if applicable). function cook( uint8[] calldata actions, uint256[] calldata values, bytes[] calldata datas ) external payable returns (uint256 value1, uint256 value2) { CookStatus memory status; for (uint256 i = 0; i < actions.length; i++) { uint8 action = actions[i]; if (!status.hasAccrued && action < 10) { accrue(); status.hasAccrued = true; } if (action == ACTION_ADD_COLLATERAL) { (int256 share, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); addCollateral(to, skim, _num(share, value1, value2)); } else if (action == ACTION_REPAY) { (int256 part, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); _repay(to, skim, _num(part, value1, value2)); } else if (action == ACTION_REMOVE_COLLATERAL) { (int256 share, address to) = abi.decode(datas[i], (int256, address)); _removeCollateral(to, _num(share, value1, value2)); status.needsSolvencyCheck = true; } else if (action == ACTION_BORROW) { (int256 amount, address to) = abi.decode(datas[i], (int256, address)); (value1, value2) = _borrow(to, _num(amount, value1, value2)); status.needsSolvencyCheck = true; } else if (action == ACTION_UPDATE_EXCHANGE_RATE) { (bool must_update, uint256 minRate, uint256 maxRate) = abi.decode(datas[i], (bool, uint256, uint256)); (bool updated, uint256 rate) = updateExchangeRate(); require((!must_update || updated) && rate > minRate && (maxRate == 0 || rate > maxRate), "Cauldron: rate not ok"); } else if (action == ACTION_BENTO_SETAPPROVAL) { (address user, address _masterContract, bool approved, uint8 v, bytes32 r, bytes32 s) = abi.decode(datas[i], (address, address, bool, uint8, bytes32, bytes32)); bentoBox.setMasterContractApproval(user, _masterContract, approved, v, r, s); } else if (action == ACTION_BENTO_DEPOSIT) { (value1, value2) = _bentoDeposit(datas[i], values[i], value1, value2); } else if (action == ACTION_BENTO_WITHDRAW) { (value1, value2) = _bentoWithdraw(datas[i], value1, value2); } else if (action == ACTION_BENTO_TRANSFER) { (IERC20 token, address to, int256 share) = abi.decode(datas[i], (IERC20, address, int256)); bentoBox.transfer(token, msg.sender, to, _num(share, value1, value2)); } else if (action == ACTION_BENTO_TRANSFER_MULTIPLE) { (IERC20 token, address[] memory tos, uint256[] memory shares) = abi.decode(datas[i], (IERC20, address[], uint256[])); bentoBox.transferMultiple(token, msg.sender, tos, shares); } else if (action == ACTION_CALL) { (bytes memory returnData, uint8 returnValues) = _call(values[i], datas[i], value1, value2); if (returnValues == 1) { (value1) = abi.decode(returnData, (uint256)); } else if (returnValues == 2) { (value1, value2) = abi.decode(returnData, (uint256, uint256)); } } else if (action == ACTION_GET_REPAY_SHARE) { int256 part = abi.decode(datas[i], (int256)); value1 = bentoBox.toShare(magicInternetMoney, totalBorrow.toElastic(_num(part, value1, value2), true), true); } else if (action == ACTION_GET_REPAY_PART) { int256 amount = abi.decode(datas[i], (int256)); value1 = totalBorrow.toBase(_num(amount, value1, value2), false); } } if (status.needsSolvencyCheck) { require(_isSolvent(msg.sender, exchangeRate), "Cauldron: user insolvent"); } } /// @notice Handles the liquidation of users' balances, once the users' amount of collateral is too low. /// @param users An array of user addresses. /// @param maxBorrowParts A one-to-one mapping to `users`, contains maximum (partial) borrow amounts (to liquidate) of the respective user. /// @param to Address of the receiver in open liquidations if `swapper` is zero. function liquidate( address[] calldata users, uint256[] calldata maxBorrowParts, address to, ISwapper swapper ) public { // Oracle can fail but we still need to allow liquidations (, uint256 _exchangeRate) = updateExchangeRate(); accrue(); uint256 allCollateralShare; uint256 allBorrowAmount; uint256 allBorrowPart; Rebase memory _totalBorrow = totalBorrow; Rebase memory bentoBoxTotals = bentoBox.totals(collateral); for (uint256 i = 0; i < users.length; i++) { address user = users[i]; if (!_isSolvent(user, _exchangeRate)) { uint256 borrowPart; { uint256 availableBorrowPart = userBorrowPart[user]; borrowPart = maxBorrowParts[i] > availableBorrowPart ? availableBorrowPart : maxBorrowParts[i]; userBorrowPart[user] = availableBorrowPart.sub(borrowPart); } uint256 borrowAmount = _totalBorrow.toElastic(borrowPart, false); uint256 collateralShare = bentoBoxTotals.toBase( borrowAmount.mul(LIQUIDATION_MULTIPLIER).mul(_exchangeRate) / (LIQUIDATION_MULTIPLIER_PRECISION * EXCHANGE_RATE_PRECISION), false ); userCollateralShare[user] = userCollateralShare[user].sub(collateralShare); emit LogRemoveCollateral(user, to, collateralShare); emit LogRepay(msg.sender, user, borrowAmount, borrowPart); // Keep totals allCollateralShare = allCollateralShare.add(collateralShare); allBorrowAmount = allBorrowAmount.add(borrowAmount); allBorrowPart = allBorrowPart.add(borrowPart); } } require(allBorrowAmount != 0, "Cauldron: all are solvent"); _totalBorrow.elastic = _totalBorrow.elastic.sub(allBorrowAmount.to128()); _totalBorrow.base = _totalBorrow.base.sub(allBorrowPart.to128()); totalBorrow = _totalBorrow; totalCollateralShare = totalCollateralShare.sub(allCollateralShare); // Apply a percentual fee share to sSpell holders { uint256 distributionAmount = (allBorrowAmount.mul(LIQUIDATION_MULTIPLIER) / LIQUIDATION_MULTIPLIER_PRECISION).sub(allBorrowAmount).mul(DISTRIBUTION_PART) / DISTRIBUTION_PRECISION; // Distribution Amount allBorrowAmount = allBorrowAmount.add(distributionAmount); accrueInfo.feesEarned = accrueInfo.feesEarned.add(distributionAmount.to128()); } uint256 allBorrowShare = bentoBox.toShare(magicInternetMoney, allBorrowAmount, true); // Swap using a swapper freely chosen by the caller // Open (flash) liquidation: get proceeds first and provide the borrow after bentoBox.transfer(collateral, address(this), to, allCollateralShare); if (swapper != ISwapper(0)) { swapper.swap(collateral, magicInternetMoney, msg.sender, allBorrowShare, allCollateralShare); } bentoBox.transfer(magicInternetMoney, msg.sender, address(this), allBorrowShare); } /// @notice Withdraws the fees accumulated. function withdrawFees() public { accrue(); address _feeTo = masterContract.feeTo(); uint256 _feesEarned = accrueInfo.feesEarned; uint256 share = bentoBox.toShare(magicInternetMoney, _feesEarned, false); bentoBox.transfer(magicInternetMoney, address(this), _feeTo, share); accrueInfo.feesEarned = 0; emit LogWithdrawFees(_feeTo, _feesEarned); } /// @notice Sets the beneficiary of interest accrued. /// MasterContract Only Admin function. /// @param newFeeTo The address of the receiver. function setFeeTo(address newFeeTo) public onlyOwner { feeTo = newFeeTo; emit LogFeeTo(newFeeTo); } /// @notice reduces the supply of MIM /// @param amount amount to reduce supply by function reduceSupply(uint256 amount) public { require(msg.sender == masterContract.owner(), "Caller is not the owner"); bentoBox.withdraw(magicInternetMoney, address(this), address(this), amount, 0); MagicInternetMoney(address(magicInternetMoney)).burn(amount); } }
elastic = Total token amount to be repayed by borrowers, base = Total parts of the debt held by borrowers
Rebase public totalBorrow;
2,271,877
[ 1, 22318, 273, 10710, 1147, 3844, 358, 506, 2071, 528, 329, 635, 29759, 414, 16, 1026, 273, 10710, 2140, 434, 326, 18202, 88, 15770, 635, 29759, 414, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 868, 1969, 1071, 2078, 38, 15318, 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 ]
./partial_match/4/0xB0C8Bd351F941b1F3e410AD74F23c484877378Fc/sources/Staking.sol
sent transfer to sender sent fee to dev
function withDrawToken(uint256 _orderId, uint256 _amount) public { Order storage order = orders[_orderId]; require(order.userId == msg.sender, 'Require created by sender'); uint256 rewardPending = _amount; uint256 feePending = 0; sendTransferReward(msg.sender, rewardPending.sub(feePending)); sendTransferReward(dev_adress, feePending); order.jusRewarded = order.jusRewarded.add(_amount); }
8,561,008
[ 1, 7569, 7412, 358, 5793, 3271, 14036, 358, 4461, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 598, 6493, 1345, 12, 11890, 5034, 389, 1019, 548, 16, 2254, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 4347, 2502, 1353, 273, 11077, 63, 67, 1019, 548, 15533, 203, 3639, 2583, 12, 1019, 18, 18991, 422, 1234, 18, 15330, 16, 296, 8115, 2522, 635, 5793, 8284, 203, 540, 203, 3639, 2254, 5034, 19890, 8579, 273, 389, 8949, 31, 203, 3639, 2254, 5034, 14036, 8579, 273, 374, 31, 203, 540, 203, 540, 203, 3639, 1366, 5912, 17631, 1060, 12, 3576, 18, 15330, 16, 19890, 8579, 18, 1717, 12, 21386, 8579, 10019, 203, 3639, 1366, 5912, 17631, 1060, 12, 5206, 67, 361, 663, 16, 14036, 8579, 1769, 203, 540, 203, 3639, 1353, 18, 78, 407, 17631, 17212, 273, 1353, 18, 78, 407, 17631, 17212, 18, 1289, 24899, 8949, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x7511EeB6d22D3f062ec72b421DEE964Ed7A24aB7/sources/contracts/ETH/aura/WETH-AURA/auraWAVault.sol
* @dev Function to send funds into the strategy and put them to work. It's primarily called by the vault's deposit() function./
function earn() public { uint _bal = available(); want().safeTransfer(address(strategy), _bal); strategy.deposit(); }
3,018,329
[ 1, 2083, 358, 1366, 284, 19156, 1368, 326, 6252, 471, 1378, 2182, 358, 1440, 18, 2597, 1807, 15610, 10243, 2566, 635, 326, 9229, 1807, 443, 1724, 1435, 445, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 425, 1303, 1435, 1071, 288, 203, 3639, 2254, 389, 70, 287, 273, 2319, 5621, 203, 3639, 2545, 7675, 4626, 5912, 12, 2867, 12, 14914, 3631, 389, 70, 287, 1769, 203, 3639, 6252, 18, 323, 1724, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.7.1; import "./BaseBidOnAddresses.sol"; /// @title Base class for a "salary" that is paid one token per second using minted conditionals. /// @author Victor Porton /// @notice Not audited, not enough tested. /// It was considered to allow the DAO to adjust registration date to pay salary retrospectively, /// but this seems giving too much rights to the DAO similarly as if it had the right to declare anyone dead. /// /// It would cause this effect: A scientist who is already great may register then his date is moved back /// in time and instantly he or she receives a very big sum of money to his account. /// If it is done erroneously, there may be no way to move the registration date again forward in time, /// because the tokens may be already withdrawn. And it cannot be done in a fully decentralized way because /// it needs oracles. So errors are seem inevitable. /// On the other hand, somebody malicious may create and register in my system a pool of Ethereum addresses that /// individuals can receive from them as if they themselves registered in the past. /// So it in some cases (if the registration date is past the contract deployment) this issue is impossible to /// mitigate. /// /// The salary is paid in minted tokens groups into "chains": /// the original salary token and anyone can replace it by another token, next in the chain. contract BaseSalary is BaseBidOnAddresses { /// Salary receiver registered. /// @param customer The customer address. /// @param oracleId The oracle ID for which he registers. /// @param data Additional data. event CustomerRegistered( address indexed customer, uint64 indexed oracleId, uint256 indexed condition, bytes data ); /// Salary tokens minted. /// @param customer The customer address. /// @param oracleId The oracle ID. /// @param amount The minted amount. /// @param data Additional data. event SalaryMinted( address indexed customer, uint64 indexed oracleId, uint256 indexed condition, uint256 amount, bytes data ); /// Salary token recreated (salary recalculation request). /// @param customer The customer address. /// @param originalCondition The original token ID. /// @param newCondition The new token ID. event ConditionReCreate( address indexed customer, uint256 indexed originalCondition, uint256 indexed newCondition ); // Mapping (condition ID => registration time). mapping(uint256 => uint) public conditionCreationDates; // Mapping (condition ID => salary block time). mapping(uint256 => uint) public lastSalaryDates; /// Mapping (condition ID => account) - salary recipients. mapping(uint256 => address) public salaryReceivers; /// Mapping (condition ID => first condition ID in the chain) /// /// I call _chain_ of conditions the list of conditions resulting from creating and recreating conditions. mapping(uint256 => uint256) public firstConditionInChain; /// Mapping (first condition ID in the chain => last condition ID in the chain) /// /// I call _chain_ of conditions the list of conditions resulting from creating and recreating conditions. mapping(uint256 => uint256) public firstToLastConditionInChain; /// Constructor. /// @param _uri The ERC-1155 token URI. constructor(string memory _uri) BaseBidOnAddresses(_uri) { } /// Mint a salary token. /// @param _oracleId The oracle ID. /// @param _condition The condition ID. /// @param _data Additional data. /// This method can be called only by the salary receiver. function mintSalary(uint64 _oracleId, uint256 _condition, bytes calldata _data) ensureLastConditionInChain(_condition) external { uint _lastSalaryDate = lastSalaryDates[_condition]; require(_lastSalaryDate != 0, "You are not registered."); // Note: Even if you withdraw once per 20 years, you will get only 630,720,000 tokens. // This number is probably not to big to be displayed well in UIs. uint256 _amount = (block.timestamp - _lastSalaryDate) * 10**18; // one token per second _mintToCustomer(msg.sender, firstToLastConditionInChain[_condition], _amount, _data); lastSalaryDates[_condition] = block.timestamp; emit SalaryMinted(msg.sender, _oracleId, _condition, _amount, _data); } /// Make a new condition that replaces the old one. /// /// In other words, it is a request to recalculate somebody's salary. /// /// Anyone can request to recalculate anyone's salary. /// /// It's also useful to punish someone for decreasing his work performance or an evil act. /// This is to be called among other when a person dies. /// /// Recalculation is also forced when a salary receiver transfers away his current salary token. /// It is useful to remove a trader's incentive to kill the issuer to reduce the circulating supply. /// /// Issue to solve later: Should we recommend: /// - calling this function on each new project milestone? /// - calling this function regularly (e.g. every week)? /// /// This function also withdraws the old token. function recreateCondition(uint256 _condition) public returns (uint256) { return _recreateCondition(_condition); } function _doCreateCondition(address _customer) internal virtual override returns (uint256) { uint256 _condition = super._doCreateCondition(_customer); salaryReceivers[_condition] = _customer; conditionCreationDates[_condition] = block.timestamp; firstConditionInChain[_condition] = _condition; firstToLastConditionInChain[_condition] = _condition; return _condition; } /// Make a new condition that replaces the old one. /// The same can be done by transferring to yourself 0 tokens, but this method uses less gas. /// /// We need to create a new condition every time when an outgoimg transfer of a conditional token happens. /// Otherwise an investor would gain if he kills a scientist to reduce the circulating supply of his token to increase the price. /// Allowing old tokens to be exchangeable for new ones? (Allowing the reverse swap would create killer's gain.) /// Additional benefit of this solution: We can have different rewards at different stages of project, /// what may be beneficial for early startups funding. /// /// Problem to be solved later: There should be an advice to switch to a new token at each milestone of a project? /// /// Anyone can create a ERC-1155 contract that allows to use any of the tokens in the list /// by locking any of the tokens in the list as a new "general" token. We should recommend customers not to /// use such contracts, because it creates for them the killer exploit. /// /// If we would exchange the old and new tokens for the same amounts of collaterals, then it would be /// effectively the same token and therefore minting more new token would possibly devalue the old one, /// thus triggering the killer's exploit again. So we make old and new completely independent. /// /// Old token is 1:1 converted to the new token. /// /// Remark: To make easy to exchange the token even if it is recreated, we can make a wrapper or locker /// token that uses `firstConditionInChain[]` to aggregate several tokens together. /// A similar wrapper (the customer need to `setApprovalForAll()` on it) that uses /// `firstToLastConditionInChain[]` can be used to transfer away recreated tokens /// even if an evil DAO tries to frontrun the customer by recreating his tokens very often. /// TODO: Test that it's possible to create such a locker. /// /// Note: That wrapper could be carelessly used to create the investor's killing customer incentive /// by the customer using it to transfer to an investor. Even if the customer uses it only for /// exchanges, an investor can buy at an exchange and be a killer. /// To make it safe, it must stop accepting any new tokens after a transfer. /// It can determine if a token is new just comparing by `<` operator. /// It's strongly recommended that an app that uses this contract provides its own swap/exchange UI /// and warns the user not to use arbitrary exchanges as being an incentive to kill the user. /// /// We allow anybody (not just the account owner or DAO) to recreate a condition, because: /// - Exchanges can create a "composite" token that allows to withdraw any of the tokens in the chain /// up to a certain period of time (using on-chain `conditionCreationDates`). /// - Therefore somebody's token can be withdrawn even if its ID changes arbitrarily often. /// /// @param _condition The condition ID. function _recreateCondition(uint256 _condition) internal ensureFirstConditionInChain(_condition) returns (uint256) { address _customer = salaryReceivers[_condition]; uint256 _oldCondition = firstToLastConditionInChain[_condition]; uint256 _newCondition = _doCreateCondition(_customer); firstConditionInChain[_newCondition] = _condition; uint256 _amount = _balances[_oldCondition][_customer]; _balances[_newCondition][_customer] = _amount; _balances[_oldCondition][_customer] = 0; // TODO: Should we swap two following lines? emit TransferSingle(msg.sender, _customer, address(0), _condition, _amount); emit TransferSingle(msg.sender, address(0), _customer, _newCondition, _amount); lastSalaryDates[_newCondition] = lastSalaryDates[_condition]; // TODO: Should we here set `lastSalaryDates[_condition] = 0` to save storage space? // TODO: It would also eliminate the need to check in mint function. emit ConditionReCreate(_customer, _condition, _newCondition); return _newCondition; } /// Check if it is the first condition in a chain of conditions. /// @param _id The condition ID. /// /// Must be called with `_id != 0`. function isFirstConditionInChain(uint256 _id) internal view returns (bool) { return firstConditionInChain[_id] == _id; } /// Check if it is the last condition in a chain of conditions. /// @param _id The condition ID. /// /// Must be called with `_id != 0`. /// /// TODO: Should make this function public? function isLastConditionInChain(uint256 _id) internal view returns (bool) { return firstToLastConditionInChain[firstConditionInChain[_id]] == _id; } function _doTransfer(uint256 _id, address _from, address _to, uint256 _value) internal virtual override { super._doTransfer(_id, _from, _to, _value); if (_id != 0 && salaryReceivers[_id] == msg.sender) { if (isLastConditionInChain(_id)) { // correct because `_id != 0` _recreateCondition(_id); } } } function _registerCustomer(address _customer, uint64 _oracleId, bytes calldata _data) virtual internal returns (uint256) { uint256 _condition = _doCreateCondition(_customer); lastSalaryDates[_condition] = block.timestamp; emit CustomerRegistered(msg.sender, _oracleId, _condition, _data); return _condition; } modifier ensureFirstConditionInChain(uint256 _id) { // TODO: Is `_id != 0` check needed? require(_isConditional(_id) && _id != 0 && isFirstConditionInChain(_id), "Only for the last salary token."); _; } modifier ensureLastConditionInChain(uint256 _id) { // TODO: Is `_id != 0` check needed? require(_isConditional(_id) && _id != 0 && isLastConditionInChain(_id), "Only for the last salary token."); _; } }
@title Base class for a "salary" that is paid one token per second using minted conditionals. @author Victor Porton @notice Not audited, not enough tested. It was considered to allow the DAO to adjust registration date to pay salary retrospectively, but this seems giving too much rights to the DAO similarly as if it had the right to declare anyone dead. It would cause this effect: A scientist who is already great may register then his date is moved back in time and instantly he or she receives a very big sum of money to his account. If it is done erroneously, there may be no way to move the registration date again forward in time, because the tokens may be already withdrawn. And it cannot be done in a fully decentralized way because it needs oracles. So errors are seem inevitable. On the other hand, somebody malicious may create and register in my system a pool of Ethereum addresses that individuals can receive from them as if they themselves registered in the past. So it in some cases (if the registration date is past the contract deployment) this issue is impossible to mitigate. The salary is paid in minted tokens groups into "chains": the original salary token and anyone can replace it by another token, next in the chain. Mapping (condition ID => registration time). Mapping (condition ID => salary block time).
contract BaseSalary is BaseBidOnAddresses { event CustomerRegistered( address indexed customer, uint64 indexed oracleId, uint256 indexed condition, bytes data ); event SalaryMinted( address indexed customer, uint64 indexed oracleId, uint256 indexed condition, uint256 amount, bytes data ); event ConditionReCreate( address indexed customer, uint256 indexed originalCondition, uint256 indexed newCondition ); mapping(uint256 => uint) public conditionCreationDates; mapping(uint256 => uint) public lastSalaryDates; mapping(uint256 => address) public salaryReceivers; mapping(uint256 => uint256) public firstConditionInChain; mapping(uint256 => uint256) public firstToLastConditionInChain; function mintSalary(uint64 _oracleId, uint256 _condition, bytes calldata _data) ensureLastConditionInChain(_condition) external pragma solidity ^0.7.1; constructor(string memory _uri) BaseBidOnAddresses(_uri) { } { uint _lastSalaryDate = lastSalaryDates[_condition]; require(_lastSalaryDate != 0, "You are not registered."); _mintToCustomer(msg.sender, firstToLastConditionInChain[_condition], _amount, _data); lastSalaryDates[_condition] = block.timestamp; emit SalaryMinted(msg.sender, _oracleId, _condition, _amount, _data); } function recreateCondition(uint256 _condition) public returns (uint256) { return _recreateCondition(_condition); } function _doCreateCondition(address _customer) internal virtual override returns (uint256) { uint256 _condition = super._doCreateCondition(_customer); salaryReceivers[_condition] = _customer; conditionCreationDates[_condition] = block.timestamp; firstConditionInChain[_condition] = _condition; firstToLastConditionInChain[_condition] = _condition; return _condition; } function _recreateCondition(uint256 _condition) internal ensureFirstConditionInChain(_condition) returns (uint256) { address _customer = salaryReceivers[_condition]; uint256 _oldCondition = firstToLastConditionInChain[_condition]; uint256 _newCondition = _doCreateCondition(_customer); firstConditionInChain[_newCondition] = _condition; uint256 _amount = _balances[_oldCondition][_customer]; _balances[_newCondition][_customer] = _amount; _balances[_oldCondition][_customer] = 0; emit TransferSingle(msg.sender, _customer, address(0), _condition, _amount); emit TransferSingle(msg.sender, address(0), _customer, _newCondition, _amount); lastSalaryDates[_newCondition] = lastSalaryDates[_condition]; emit ConditionReCreate(_customer, _condition, _newCondition); return _newCondition; } function isFirstConditionInChain(uint256 _id) internal view returns (bool) { return firstConditionInChain[_id] == _id; } function isLastConditionInChain(uint256 _id) internal view returns (bool) { return firstToLastConditionInChain[firstConditionInChain[_id]] == _id; } function _doTransfer(uint256 _id, address _from, address _to, uint256 _value) internal virtual override { super._doTransfer(_id, _from, _to, _value); if (_id != 0 && salaryReceivers[_id] == msg.sender) { _recreateCondition(_id); } } function _doTransfer(uint256 _id, address _from, address _to, uint256 _value) internal virtual override { super._doTransfer(_id, _from, _to, _value); if (_id != 0 && salaryReceivers[_id] == msg.sender) { _recreateCondition(_id); } } }
12,753,718
[ 1, 2171, 667, 364, 279, 315, 21982, 814, 6, 716, 353, 30591, 1245, 1147, 1534, 2205, 1450, 312, 474, 329, 2269, 1031, 18, 225, 776, 933, 280, 6008, 265, 225, 2288, 8215, 329, 16, 486, 7304, 18432, 18, 2597, 1703, 7399, 358, 1699, 326, 463, 20463, 358, 5765, 7914, 1509, 358, 8843, 12814, 814, 325, 26170, 4492, 16, 1496, 333, 12001, 21057, 4885, 9816, 14989, 358, 326, 463, 20463, 7281, 715, 487, 309, 518, 9323, 326, 2145, 358, 14196, 1281, 476, 8363, 18, 2597, 4102, 4620, 333, 5426, 30, 432, 888, 1979, 376, 10354, 353, 1818, 18825, 2026, 1744, 1508, 18423, 1509, 353, 10456, 1473, 316, 813, 471, 5934, 715, 3904, 578, 23901, 17024, 279, 8572, 5446, 2142, 434, 15601, 358, 18423, 2236, 18, 971, 518, 353, 2731, 393, 476, 1481, 715, 16, 1915, 2026, 506, 1158, 4031, 358, 3635, 326, 7914, 1509, 3382, 5104, 316, 813, 16, 2724, 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, 3360, 55, 287, 814, 353, 3360, 17763, 1398, 7148, 288, 203, 565, 871, 13702, 10868, 12, 203, 3639, 1758, 8808, 6666, 16, 203, 3639, 2254, 1105, 8808, 20865, 548, 16, 203, 3639, 2254, 5034, 8808, 2269, 16, 203, 3639, 1731, 501, 203, 565, 11272, 203, 203, 565, 871, 348, 287, 814, 49, 474, 329, 12, 203, 3639, 1758, 8808, 6666, 16, 203, 3639, 2254, 1105, 8808, 20865, 548, 16, 203, 3639, 2254, 5034, 8808, 2269, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1731, 501, 203, 565, 11272, 203, 203, 565, 871, 7949, 426, 1684, 12, 203, 3639, 1758, 8808, 6666, 16, 203, 3639, 2254, 5034, 8808, 2282, 3418, 16, 203, 3639, 2254, 5034, 8808, 394, 3418, 203, 565, 11272, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 13, 1071, 2269, 9906, 15578, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 13, 1071, 1142, 55, 287, 814, 15578, 31, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 1071, 12814, 814, 4779, 6760, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 1122, 3418, 382, 3893, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 1122, 774, 3024, 3418, 382, 3893, 31, 203, 203, 203, 565, 445, 312, 474, 55, 287, 814, 12, 11890, 1105, 389, 280, 16066, 548, 16, 2254, 5034, 389, 4175, 16, 1731, 745, 892, 389, 892, 13, 203, 3639, 3387, 3024, 3418, 382, 3893, 24899, 4175, 13, 3903, 203, 683, 9454, 18035, 560, 3602, 20, 18, 27, 18, 21, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-05-21 */ pragma solidity ^0.5.0; // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Safe Math Library // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } contract DigitalYuan is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "DigitalYuan"; symbol = "DYT"; decimals = 2; _totalSupply = 100000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } }
* Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
constructor() public { name = "DigitalYuan"; symbol = "DYT"; decimals = 2; _totalSupply = 100000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); }
2,092,265
[ 1, 442, 701, 30206, 445, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 1071, 288, 203, 3639, 508, 273, 315, 4907, 7053, 61, 89, 304, 14432, 203, 3639, 3273, 273, 315, 40, 61, 56, 14432, 203, 3639, 15105, 273, 576, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 2787, 9449, 31, 203, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0xdcd943aA33B1748704C70d961b9D857F8C610BEd/sources/contracts/Contract.sol
Add the current token to the hierarchy
uplinesHierarchy[tokenId].push(tokenId);
3,790,861
[ 1, 986, 326, 783, 1147, 358, 326, 9360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 582, 412, 1465, 12074, 63, 2316, 548, 8009, 6206, 12, 2316, 548, 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 ]
./full_match/1/0x03D6e6b89447dDddB382F60a2b59B877Ae815A7c/sources/Context.sol
* @dev Provides information about the current execution context, including the sender of the transaction and its data. While these are generally available via msg.sender and msg.data, they should not be accessed in such a direct manner, since when dealing with meta-transactions the account sending and paying for execution may not be the actual sender (as far as an application is concerned). This contract is only required for intermediate, library-like contracts./
abstract contract Context { Automating unique ETH address generation. Secure & distinctive. 🔐 function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
4,841,993
[ 1, 17727, 1779, 2973, 326, 783, 4588, 819, 16, 6508, 326, 5793, 434, 326, 2492, 471, 2097, 501, 18, 21572, 4259, 854, 19190, 2319, 3970, 1234, 18, 15330, 471, 1234, 18, 892, 16, 2898, 1410, 486, 506, 15539, 316, 4123, 279, 2657, 21296, 16, 3241, 1347, 21964, 598, 2191, 17, 20376, 326, 2236, 5431, 471, 8843, 310, 364, 4588, 2026, 486, 506, 326, 3214, 5793, 261, 345, 10247, 487, 392, 2521, 353, 356, 2750, 11748, 2934, 1220, 6835, 353, 1338, 1931, 364, 12110, 16, 5313, 17, 5625, 20092, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 1772, 288, 203, 203, 22932, 1776, 3089, 512, 2455, 1758, 9377, 18, 15653, 473, 10217, 688, 18, 225, 177, 258, 247, 243, 203, 203, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 1476, 5024, 1135, 261, 2867, 13, 288, 203, 3639, 327, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 751, 1435, 2713, 1476, 5024, 1135, 261, 3890, 745, 892, 13, 288, 203, 3639, 327, 1234, 18, 892, 31, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * @authors: [@unknownunknown1] * @reviewers: [] * @auditors: [] * @bounties: [] * @deployments: [] */ /* solium-disable security/no-block-members */ /* solium-disable max-len */ /* solium-disable security/no-send */ pragma solidity ^0.4.24; import { Arbitrable, Arbitrator } from "../arbitration/Arbitrable.sol"; import "../../libraries/CappedMath.sol"; interface RealitioInterface { /// @notice Notify the contract that the arbitrator has been paid for a question, freezing it pending their decision. /// @dev The arbitrator contract is trusted to only call this if they've been paid, and tell us who paid them. /// @param question_id The ID of the question. /// @param requester The account that requested arbitration. /// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction. function notifyOfArbitrationRequest(bytes32 question_id, address requester, uint256 max_previous) external; /// @notice Submit the answer for a question, for use by the arbitrator. /// @dev Doesn't require (or allow) a bond. /// If the current final answer is correct, the account should be whoever submitted it. /// If the current final answer is wrong, the account should be whoever paid for arbitration. /// However, the answerer stipulations are not enforced by the contract. /// @param question_id The ID of the question. /// @param answer The answer, encoded into bytes32. /// @param answerer The account credited with this answer for the purpose of bond claims. function submitAnswerByArbitrator(bytes32 question_id, bytes32 answer, address answerer) external; /// @notice Returns the history hash of the question. /// @param question_id The ID of the question. /// @dev Updated on each answer, then rewound as each is claimed. function getHistoryHash(bytes32 question_id) external returns(bytes32); /// @notice Returns the commitment info by its id. /// @param commitment_id The ID of the commitment. /// @return Time after which the committed answer can be revealed. /// @return Whether the commitment has already been revealed or not. /// @return The committed answer, encoded as bytes32. function commitments(bytes32 commitment_id) external returns(uint32, bool, bytes32); } /** * @title RealitioArbitratorProxy * @dev A Realitio arbitrator that is just a proxy for an ERC792 arbitrator. * This version of the contract supports the appeal crowdfunding and evidence submission. * NOTE: This contract trusts that the Arbitrator is honest and will not reenter or modify its costs during a call. * The arbitrator must support appeal period. */ contract RealitioArbitratorProxyWithAppeals is Arbitrable { using CappedMath for uint; /* Events */ /** @dev Emitted when arbitration is requested, to link dispute ID to question ID for UIs. * @param _disputeID The ID of the dispute in the ERC792 arbitrator. * @param _questionID The ID of the question. */ event DisputeIDToQuestionID(uint indexed _disputeID, bytes32 _questionID); /* Storage */ struct Question { uint disputeID; // The ID of the dispute raised in the arbitrator contract. bool disputed; // Whether the answer to the question was disputed or not. address disputer; // The address that requested the arbitration. bytes32 answer; // The answer given by the arbitrator converted to bytes32. uint ruling; // The answer given by the arbitrator but in the default uint type. bool ruled; // Whether the ruling has already been given or not. bool reported; // Whether the answer has been reported to Realitio or not. Round[] rounds; // Tracks each appeal round of a dispute. uint shadowWinner; // The first answer that has been funded in the last round. If it stays the only funded answer, it will win regardless of the final ruling. } // The answer is stored in the uint type to match the arbitrator's ruling. struct Round { mapping (uint => uint) paidFees; // Tracks the fees paid by each side in this round in the form paidFees[answer]. mapping (uint => bool) hasPaid; // True if the fees for this particular answer has been fully paid in the form hasPaid[answer]. uint feeRewards; // Sum of reimbursable fees and stake rewards available to the parties that made contributions to the side that ultimately wins a dispute. mapping(address => mapping (uint => uint)) contributions; // Maps contributors to their contributions for each answer in the form contributions[address][answer]. uint successfullyPaid; // Sum of all successfully paid fees paid by all sides. uint[] fundedAnswers; // Stores the answers that received contributions in this round. mapping(uint => bool) answerAdded; // True if the answer has already been added to the fundedAnswers array. } address public deployer; // The address of the deployer of the contract. address public governor; // The address that can make governance changes. RealitioInterface public realitio; // The address of the Realitio contract. // In order to fund an appeal only two possible answers have to be funded. The answer has a uint type to match the arbitrator's ruling and is capped with 2**256 - 2. uint public constant NUMBER_OF_CHOICES_FOR_ARBITRATOR = (2 ** 256) - 2; // The number of choices for the ERC792 arbitrator. uint public constant NO_SHADOW_WINNER = uint(-1); // The value that indicates that no one has successfully paid appeal fees in a current round. It's the largest integer and not 0, because 0 can be a valid ruling. // Multipliers are in basis points. uint public sharedMultiplier; // Multiplier for calculating the appeal fee that must be paid by each side in the case where there is no winner/loser (e.g. when the arbitrator ruled "refuse to arbitrate"). uint public winnerMultiplier; // Multiplier for calculating the appeal fee of the party that won the previous round. uint public loserMultiplier; // Multiplier for calculating the appeal fee of the party that lost the previous round. uint public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers. mapping(uint => bytes32) public disputeIDToQuestionID; // Maps a dispute ID to the ID of the disputed question. disputeIDToQuestionID[disputeID]. mapping (bytes32 => Question) public questions; // Maps a question ID to its data. questions[question]. /* Constructor */ /** @dev Constructs the RealitioArbitratorProxy contract. * @param _arbitrator The address of the ERC792 arbitrator. * @param _arbitratorExtraData The extra data used to raise a dispute in the ERC792 arbitrator. * @param _realitio The address of the Realitio contract. * @param _sharedMultiplier Multiplier of the arbitration cost that each party must pay as fee stake for a round when there is not winner or loser in the previous round. In basis points. * @param _winnerMultiplier Multiplier of the arbitration cost that the winner has to pay as fee stake for a round in basis points. * @param _loserMultiplier Multiplier of the arbitration cost that the loser has to pay as fee stake for a round in basis points. */ constructor( Arbitrator _arbitrator, bytes _arbitratorExtraData, RealitioInterface _realitio, uint _sharedMultiplier, uint _winnerMultiplier, uint _loserMultiplier ) Arbitrable(_arbitrator, _arbitratorExtraData) public { deployer = msg.sender; governor = msg.sender; realitio = _realitio; sharedMultiplier = _sharedMultiplier; winnerMultiplier = _winnerMultiplier; loserMultiplier = _loserMultiplier; } /* External */ /** @dev Sets the meta evidence. Can only be called once. * @param _metaEvidence The URI of the meta evidence file. */ function setMetaEvidence(string _metaEvidence) external { require(msg.sender == deployer, "Can only be called once by the deployer of the contract."); deployer = address(0); emit MetaEvidence(0, _metaEvidence); } /** @dev Changes the proportion of appeal fees that must be paid when there is no winner or loser. * @param _sharedMultiplier The new shared multiplier value in basis points. */ function changesharedMultiplier(uint _sharedMultiplier) external { require(msg.sender == governor, "Only the governor can execute this."); sharedMultiplier = _sharedMultiplier; } /** @dev Changes the proportion of appeal fees that must be added to appeal cost for the winning party. * @param _winnerMultiplier The new winner multiplier value in basis points. */ function changeWinnerMultiplier(uint _winnerMultiplier) external { require(msg.sender == governor, "Only the governor can execute this."); winnerMultiplier = _winnerMultiplier; } /** @dev Changes the proportion of appeal fees that must be added to appeal cost for the losing party. * @param _loserMultiplier The new loser multiplier value in basis points. */ function changeLoserMultiplier(uint _loserMultiplier) external { require(msg.sender == governor, "Only the governor can execute this."); loserMultiplier = _loserMultiplier; } /** @dev Raise a dispute from a specified question. UNTRUSTED. * @param _questionID The ID of the question. * @param _maxPrevious If specified, reverts if a bond higher than this was submitted after you sent your transaction. */ function requestArbitration(bytes32 _questionID, uint _maxPrevious) external payable { Question storage question = questions[_questionID]; require(question.disputer == address(0), "The arbitration has already been requested."); question.disputer = msg.sender; question.disputeID = arbitrator.createDispute.value(msg.value)(NUMBER_OF_CHOICES_FOR_ARBITRATOR, arbitratorExtraData); disputeIDToQuestionID[question.disputeID] = _questionID; question.disputed = true; question.shadowWinner = NO_SHADOW_WINNER; question.rounds.length++; realitio.notifyOfArbitrationRequest(_questionID, msg.sender, _maxPrevious); emit Dispute(arbitrator, question.disputeID, 0, 0); emit DisputeIDToQuestionID(question.disputeID, _questionID); } /** @dev Takes up to the total amount required to fund a side of an appeal. Reimburses the rest. Creates an appeal if at least two answers are funded. TRUSTED. * @param _disputeID The ID of the dispute raised by the arbitrator for the particular question. * @param _answer One of the possible rulings the arbitrator can give that the funder considers to be the correct answer to the question. */ function fundAppeal(uint _disputeID, uint _answer) external payable { Question storage question = questions[disputeIDToQuestionID[_disputeID]]; require(_answer != uint(-1), "The answer is out of bounds."); require(question.disputed, "No dispute to appeal."); (uint appealPeriodStart, uint appealPeriodEnd) = arbitrator.appealPeriod(question.disputeID); require( now >= appealPeriodStart && now < appealPeriodEnd, "Appeal fees must be paid within the appeal period." ); uint winner = arbitrator.currentRuling(question.disputeID); uint multiplier; if (winner == _answer) { multiplier = winnerMultiplier; } else if (winner == 0) { multiplier = sharedMultiplier; } else { require(now - appealPeriodStart < (appealPeriodEnd - appealPeriodStart)/2, "The loser must pay during the first half of the appeal period."); multiplier = loserMultiplier; } Round storage round = question.rounds[question.rounds.length - 1]; require(!round.hasPaid[_answer], "Appeal fee has already been paid."); uint appealCost = arbitrator.appealCost(question.disputeID, arbitratorExtraData); uint totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR); // Take up to the amount necessary to fund the current round at the current costs. uint contribution; // Amount contributed. uint remainingETH; // Remaining ETH to send back. (contribution, remainingETH) = calculateContribution(msg.value, totalCost.subCap(round.paidFees[_answer])); round.contributions[msg.sender][_answer] += contribution; round.paidFees[_answer] += contribution; if (!round.answerAdded[_answer] && contribution > 0) { round.fundedAnswers.push(_answer); round.answerAdded[_answer] = true; } // Add contribution to reward when the fee funding is successful, otherwise it can be withdrawn later. if (round.paidFees[_answer] >= totalCost) { round.hasPaid[_answer] = true; if (question.shadowWinner == NO_SHADOW_WINNER) question.shadowWinner = _answer; round.feeRewards += round.paidFees[_answer]; round.successfullyPaid += round.paidFees[_answer]; } // Reimburse leftover ETH. msg.sender.send(remainingETH); if (question.shadowWinner != NO_SHADOW_WINNER && question.shadowWinner != _answer && round.hasPaid[_answer]) { // Two sides are fully funded. question.shadowWinner = NO_SHADOW_WINNER; arbitrator.appeal.value(appealCost)(question.disputeID, arbitratorExtraData); question.rounds.length++; round.feeRewards = round.feeRewards.subCap(appealCost); } } /** @dev Sends the fee stake rewards and reimbursements proportional to the contributions made to the winner of a dispute. Reimburses contributions if there is no winner. * @param _disputeID The ID of the dispute raised by the arbitrator for the particular question. * @param _beneficiary The address that made contributions. * @param _round The round from which to withdraw. * @param _answer The answer the beneficiary contributed to. */ function withdrawFeesAndRewards(uint _disputeID, address _beneficiary, uint _round, uint _answer) public { Question storage question = questions[disputeIDToQuestionID[_disputeID]]; Round storage round = question.rounds[_round]; require(question.ruled, "The dispute for the question should be resolved."); uint reward; // Allow to reimburse if funding of the round was unsuccessful. if (!round.hasPaid[_answer]) { reward = round.contributions[_beneficiary][_answer]; } else if (question.ruling == 0 || !round.hasPaid[question.ruling]) { // Reimburse unspent fees proportionally if there is no winner and loser. Also applies to the situation where the ultimate winner didn't pay appeal fees fully. reward = round.successfullyPaid > 0 ? (round.contributions[_beneficiary][_answer] * round.feeRewards) / round.successfullyPaid : 0; } else if (question.ruling == _answer) { // Reward the winner. reward = round.paidFees[_answer] > 0 ? (round.contributions[_beneficiary][_answer] * round.feeRewards) / round.paidFees[_answer] : 0; } round.contributions[_beneficiary][_answer] = 0; _beneficiary.send(reward); // It is the user responsibility to accept ETH. } /** @dev Report the answer to a specified question from the ERC792 arbitrator to the Realitio contract. TRUSTED. * @param _questionID The ID of the question. * @param _lastHistoryHash The history hash given with the last answer to the question in the Realitio contract. * @param _lastAnswerOrCommitmentID The last answer given, or its commitment ID if it was a commitment, to the question in the Realitio contract. * @param _lastBond The bond paid for the last answer to the question in the Realitio contract. * @param _lastAnswerer The last answerer to the question in the Realitio contract. * @param _isCommitment Whether the last answer to the question in the Realitio contract used commit or reveal or not. True if it did, false otherwise. */ function reportAnswer( bytes32 _questionID, bytes32 _lastHistoryHash, bytes32 _lastAnswerOrCommitmentID, uint _lastBond, address _lastAnswerer, bool _isCommitment ) external { Question storage question = questions[_questionID]; require( realitio.getHistoryHash(_questionID) == keccak256(_lastHistoryHash, _lastAnswerOrCommitmentID, _lastBond, _lastAnswerer, _isCommitment), "The hash of the history parameters supplied does not match the one stored in the Realitio contract." ); require(!question.reported, "The answer has already been reported for this question."); require(question.ruled, "The arbitrator has not ruled yet."); question.reported = true; realitio.submitAnswerByArbitrator( _questionID, question.answer, computeWinner(_questionID, _lastAnswerOrCommitmentID, _lastBond, _lastAnswerer, _isCommitment) ); } /** @dev Allows to submit evidence for a given dispute. * @param _disputeID The ID of the dispute raised by the arbitrator for the particular question. * @param _evidenceURI Link to evidence. */ function submitEvidence(uint _disputeID, string _evidenceURI) external { bytes32 questionID = disputeIDToQuestionID[_disputeID]; Question storage question = questions[questionID]; require(question.disputer != address(0), "The arbitration for this question has not been requested."); require(question.ruled == false, "Cannot submit evidence to a resolved dispute."); emit Evidence(arbitrator, uint(questionID), msg.sender, _evidenceURI); } /** @dev Gives a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Refuse to arbitrate". */ function rule(uint _disputeID, uint _ruling) public { Question storage question = questions[disputeIDToQuestionID[_disputeID]]; require(msg.sender == address(arbitrator), "Must be called by the arbitrator."); require(!question.ruled, "The dispute has already been resolved."); require(_ruling <= NUMBER_OF_CHOICES_FOR_ARBITRATOR, "Ruling is out of bounds."); // If one side paid its fees, the ruling is in its favor. Note that if the other side had also paid, an appeal would have been created. if (question.shadowWinner != NO_SHADOW_WINNER) executeRuling(_disputeID, question.shadowWinner); else executeRuling(_disputeID, _ruling); } /* External Views */ /** @dev Get the fee for a dispute from a specified question. UNTRUSTED. * @param _questionID The ID of the question. * @return fee The dispute's fee. */ function getDisputeFee(bytes32 _questionID) external view returns (uint fee) { return arbitrator.arbitrationCost(arbitratorExtraData); } /** @dev Gets the contributions made for a given round. * Note that this function is O(n), where n is the total number of answers funded in the round. This could exceed the gas limit, therefore this function should only be used for interface display and not by other contracts. * @param _disputeID ID of the dispute related to the queried question. * @param _round The round to query. * @param _contributor The address of the contributor. * @return fundedAnswers The answers that were funded in this round. * @return contributions The contributions. */ function getContributions( uint _disputeID, uint _round, address _contributor ) public view returns( uint[] fundedAnswers, uint[] contributions ) { Question storage question = questions[disputeIDToQuestionID[_disputeID]]; Round storage round = question.rounds[_round]; fundedAnswers = round.fundedAnswers; contributions = new uint[](round.fundedAnswers.length); for (uint i = 0; i < contributions.length; i++) { contributions[i] = round.contributions[_contributor][fundedAnswers[i]]; } } /** @dev Gets the information on a round of a session. * Note that this function is O(n), where n is the total number of answers funded in the round. This could exceed the gas limit, therefore this function should only be used for interface display and not by other contracts. * @param _disputeID ID of the dispute related to the queried question. * @param _round The round to query. * @return The round information. */ function getRoundInfo(uint _disputeID, uint _round) public view returns ( uint[] paidFees, bool[] hasPaid, uint feeRewards, uint successfullyPaid ) { Question storage question = questions[disputeIDToQuestionID[_disputeID]]; Round storage round = question.rounds[_round]; paidFees = new uint[](round.fundedAnswers.length); hasPaid = new bool[](round.fundedAnswers.length); for (uint i = 0; i < round.fundedAnswers.length; i++) { paidFees[i] = round.paidFees[round.fundedAnswers[i]]; hasPaid[i] = round.hasPaid[round.fundedAnswers[i]]; } feeRewards = round.feeRewards; successfullyPaid = round.successfullyPaid; } /* Internal */ /** @dev Returns the contribution value and remainder from available ETH and required amount. * @param _available The amount of ETH available for the contribution. * @param _requiredAmount The amount of ETH required for the contribution. * @return taken The amount of ETH taken. * @return remainder The amount of ETH left from the contribution. */ function calculateContribution(uint _available, uint _requiredAmount) internal pure returns(uint taken, uint remainder) { if (_requiredAmount > _available) taken = _available; else { taken = _requiredAmount; remainder = _available - _requiredAmount; } } /** @dev Execute the ruling of a specified dispute. * @param _disputeID The ID of the dispute in the ERC792 arbitrator. * @param _ruling The ruling given by the ERC792 arbitrator. Note that 0 is reserved for "Unable/refused to arbitrate" and we map it to `bytes32(-1)` which has a similar connotation in Realitio. */ function executeRuling(uint _disputeID, uint _ruling) internal { Question storage question = questions[disputeIDToQuestionID[_disputeID]]; question.answer = bytes32(_ruling == 0 ? uint(-1) : _ruling - 1); question.ruling = _ruling; question.ruled = true; } /* Private Views */ /** @dev Computes the Realitio answerer, of a specified question, that should win. This function is needed to avoid the "stack too deep error". TRUSTED. * @param _questionID The ID of the question. * @param _lastAnswerOrCommitmentID The last answer given, or its commitment ID if it was a commitment, to the question in the Realitio contract. * @param _lastBond The bond paid for the last answer to the question in the Realitio contract. * @param _lastAnswerer The last answerer to the question in the Realitio contract. * @param _isCommitment Whether the last answer to the question in the Realitio contract used commit or reveal or not. True if it did, false otherwise. * @return winner The computed winner. */ function computeWinner( bytes32 _questionID, bytes32 _lastAnswerOrCommitmentID, uint _lastBond, address _lastAnswerer, bool _isCommitment ) private view returns(address winner) { bytes32 lastAnswer; bool isAnswered; Question storage question = questions[_questionID]; if (_lastBond == 0) { // If the question hasn't been answered, nobody is ever right. isAnswered = false; } else if (_isCommitment) { (uint32 revealTS, bool isRevealed, bytes32 revealedAnswer) = realitio.commitments(_lastAnswerOrCommitmentID); if (isRevealed) { lastAnswer = revealedAnswer; isAnswered = true; } else { require(revealTS <= uint32(now), "Arbitration cannot be done until the last answerer has had time to reveal its commitment."); isAnswered = false; } } else { lastAnswer = _lastAnswerOrCommitmentID; isAnswered = true; } return isAnswered && lastAnswer == question.answer ? _lastAnswerer : question.disputer; } }
The first answer that has been funded in the last round. If it stays the only funded answer, it will win regardless of the final ruling.
uint shadowWinner;
5,511,454
[ 1, 1986, 1122, 5803, 716, 711, 2118, 9831, 785, 316, 326, 1142, 3643, 18, 971, 518, 384, 8271, 326, 1338, 9831, 785, 5803, 16, 518, 903, 5657, 15255, 434, 326, 727, 436, 332, 310, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 10510, 59, 7872, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false // Consensus list of airlines mapping (address => uint256) private authorizedContracts; // Consensus mapping. // Airline mapping mapping(address => address[]) private airlineConcensusList; // Mapping Contact active consensus mapping(address => uint256) private airlineConcensusTotal; // Checks Change to one contract... // mapping (address => uint256) private authorizedUsersCont; // airlines struct // addresses, funds and approved status from consesus. struct Airline { address airlineAddress; uint256 funds; bool status; } // All airlines mapping (address => Airline) private airlines; // Total airlines before we start consensus uint256 private airlineCounter = 0 ; // Passengers struct Insurance { bool refunded; bool claimed; string flight; address passenger; uint256 value; } mapping(bytes32 => Insurance) private insuredFlights; mapping(string => address[]) private flightPassengers; mapping(address => uint256) private passengerFunds; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor() public { contractOwner = msg.sender; authorizedContracts[msg.sender] = 1; airlines[msg.sender]=Airline({ airlineAddress: msg.sender, funds:0, status:true }); airlineCounter = airlineCounter.add(1); } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } // Making sure its an authorized contract performing the changes. modifier isCallerAuthorized() { require(authorizedContracts[msg.sender] == 1, "Caller is not authorized"); _; } // Contract authorization functuons!!! function authorizeCaller(address dataContract) external requireContractOwner{ authorizedContracts[dataContract] = 1; } function deauthorizeCaller(address dataContract) external requireContractOwner{ delete authorizedContracts[dataContract]; } // AIRLINE Modifiers // Airline is approved modifier approvedAirline() { require(airlines[msg.sender].status, "Airline is not approved"); _; } // Airline has funds modifier fundedAirline() { require(airlines[msg.sender].funds > 0, "Airline doesnt have funds"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus(bool mode) public requireContractOwner { operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ // Airlines /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline(address airlineAddress, uint256 funds, bool status ) isCallerAuthorized external { airlines[airlineAddress]=Airline({ airlineAddress: airlineAddress, funds:funds, status:status }); airlineCounter = airlineCounter.add(1); } function setAirlineFunds(address airlineAddress, uint256 funds) external payable isCallerAuthorized { airlines[airlineAddress].funds = airlines[airlineAddress].funds.add(funds); } // Getting amount of Airlines already in the system. function getAirlineCounter() external view returns (uint256) { return airlineCounter; } // Adding airline concensus function addConcensus(address airlineToApprove, address approvingAirline, uint256 vote) external isCallerAuthorized returns (uint256) { for (uint i=0; i<airlineConcensusList[airlineToApprove].length; i++) { if(airlineConcensusList[airlineToApprove][i] == approvingAirline){ require(false, "User already voted."); } } airlineConcensusList[airlineToApprove].push(approvingAirline); airlineConcensusTotal[airlineToApprove] = airlineConcensusTotal[airlineToApprove].add(vote); return airlineConcensusTotal[airlineToApprove]; } // Function to check total votes for an airline. function getAirlineVotes(address airlineAddress) external view isCallerAuthorized returns (uint256 votes){ return airlineConcensusTotal[airlineAddress]; } // Get airline information from Adress function getAirlines(address airlineAddress ) external view isCallerAuthorized returns (address airline, uint256 funds, bool status) { Airline memory airlineData = airlines[airlineAddress]; return (airlineData.airlineAddress, airlineData.funds, airlineData.status); } // Get airline status from Adress function getAirlineStatus(address airlineAddress ) external view isCallerAuthorized returns (bool status) { Airline memory airlineData = airlines[airlineAddress]; return airlineData.status; } // Passengers!!! /** * @dev Buy insurance for a flight * */ function buyInsurace(string flight, address passenger) isCallerAuthorized external payable { Insurance memory temp = Insurance({ refunded:false, claimed:false, flight: flight, passenger: passenger, value: msg.value }); bytes32 key = keccak256(abi.encodePacked(flight, passenger)); insuredFlights[key] = temp; flightPassengers[flight].push(passenger); } function contractBalance() external view returns(uint) { return address(this).balance; } // Retrieve insurance function getInsurance(string flight, address passenger) isCallerAuthorized external view returns (address r_passenger, string r_flight, uint256 value, bool claimed){ bytes32 key = keccak256(abi.encodePacked(flight, passenger)); return (insuredFlights[key].passenger, insuredFlights[key].flight, insuredFlights[key].value, insuredFlights[key].claimed); } /** * @dev Credits payouts to insurees give credit to users before paying them. */ function creditInsurees( string flight ) isCallerAuthorized external { address[] memory passengers = flightPassengers[flight]; for (uint i=0; i<passengers.length; i++) { bytes32 key = keccak256(abi.encodePacked(flight, passengers[i])); Insurance storage passengerInsurance = insuredFlights[key]; // multiply by 3 and divide by 2 == 1.5 uint256 multiplied = passengerInsurance.value.mul(3).div(2); passengerFunds[passengers[i]] = passengerFunds[passengers[i]].add(multiplied); passengerInsurance.refunded = true; insuredFlights[key] = passengerInsurance; } } function getPassengerFunds(address passenger) external view isCallerAuthorized returns (uint256 funds) { return passengerFunds[passenger]; } /** * @dev Transfers eligible payout funds to insuree * basically withdraw */ function pay(address passenger, uint256 value) isCallerAuthorized external { passengerFunds[passenger] = 0; passenger.transfer(value); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * airline activation 10 ether * */ function fund ( ) public payable { } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(); } }
Total airlines before we start consensus
uint256 private airlineCounter = 0 ;
5,527,199
[ 1, 5269, 23350, 3548, 1865, 732, 787, 18318, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 3238, 23350, 1369, 4789, 273, 374, 274, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-11-03 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /** * @dev ERC-721 non-fungible token standard. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md. */ interface ERC721 { /** * @dev 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 ); /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice 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. 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,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 calldata _data ) external; /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice 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; /** * @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. * @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else * they mayb be permanently lost. * @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 ) external; /** * @dev Set or reaffirm the approved address for an NFT. * @notice 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; /** * @dev Enables or disables approval for a third party ("operator") to manage all of * `msg.sender`'s assets. It also emits the ApprovalForAll event. * @notice The contract MUST allow multiple operators per owner. * @param _operator Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval. */ function setApprovalForAll( address _operator, bool _approved ) external; /** * @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are * considered invalid, and this function throws for queries about the zero address. * @param _owner Address for whom to query the balance. * @return Balance of _owner. */ function balanceOf( address _owner ) external view returns (uint256); /** * @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered * invalid, and queries about them do throw. * @param _tokenId The identifier for an NFT. * @return Address of _tokenId owner. */ function ownerOf( uint256 _tokenId ) external view returns (address); /** * @dev Get the approved address for a single NFT. * @notice Throws if `_tokenId` is not a valid NFT. * @param _tokenId The NFT to find the approved address for. * @return Address that _tokenId is approved for. */ function getApproved( uint256 _tokenId ) external view returns (address); /** * @dev Returns true if `_operator` is an approved operator for `_owner`, false otherwise. * @param _owner The address that owns the NFTs. * @param _operator The address that acts on behalf of the owner. * @return True if approved for all, false otherwise. */ function isApprovedForAll( address _owner, address _operator ) external view returns (bool); } /** * @dev ERC-721 interface for accepting safe transfers. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md. */ interface ERC721TokenReceiver { /** * @dev Handle the receipt of a NFT. The ERC721 smart contract calls this function on the * recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return * of other than the magic value MUST result in the transaction being reverted. * Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` unless throwing. * @notice The contract address is always the message sender. A wallet/broker/auction application * MUST implement the wallet interface if it will accept safe transfers. * @param _operator The address which called `safeTransferFrom` function. * @param _from The address which previously owned the token. * @param _tokenId The NFT identifier which is being transferred. * @param _data Additional data with no specified format. * @return Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata _data ) external returns(bytes4); } /** * @dev Math operations with safety checks that throw on error. */ library SafeMath { string constant OVERFLOW = "008001"; string constant SUBTRAHEND_GREATER_THEN_MINUEND = "008002"; string constant DIVISION_BY_ZERO = "008003"; /** * @dev Multiplies two numbers, reverts on overflow. * @param _factor1 Factor number. * @param _factor2 Factor number. * @return product The product of the two factors. */ function mul( uint256 _factor1, uint256 _factor2 ) internal pure returns (uint256 product) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. if (_factor1 == 0) { return 0; } product = _factor1 * _factor2; require(product / _factor1 == _factor2, OVERFLOW); } /** * @dev Integer division of two numbers, truncating the quotient, reverts on division by zero. * @param _dividend Dividend number. * @param _divisor Divisor number. * @return quotient The quotient. */ function div( uint256 _dividend, uint256 _divisor ) internal pure returns (uint256 quotient) { // Solidity automatically asserts when dividing by 0, using all gas. require(_divisor > 0, DIVISION_BY_ZERO); quotient = _dividend / _divisor; // assert(_dividend == _divisor * quotient + _dividend % _divisor); // There is no case in which this doesn't hold. } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). * @param _minuend Minuend number. * @param _subtrahend Subtrahend number. * @return difference Difference. */ function sub( uint256 _minuend, uint256 _subtrahend ) internal pure returns (uint256 difference) { require(_subtrahend <= _minuend, SUBTRAHEND_GREATER_THEN_MINUEND); difference = _minuend - _subtrahend; } /** * @dev Adds two numbers, reverts on overflow. * @param _addend1 Number. * @param _addend2 Number. * @return sum Sum. */ function add( uint256 _addend1, uint256 _addend2 ) internal pure returns (uint256 sum) { sum = _addend1 + _addend2; require(sum >= _addend1, OVERFLOW); } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), reverts when * dividing by zero. * @param _dividend Number. * @param _divisor Number. * @return remainder Remainder. */ function mod( uint256 _dividend, uint256 _divisor ) internal pure returns (uint256 remainder) { require(_divisor != 0, DIVISION_BY_ZERO); remainder = _dividend % _divisor; } } /** * @dev A standard for detecting smart contract interfaces. * See: https://eips.ethereum.org/EIPS/eip-165. */ interface ERC165 { /** * @dev Checks if the smart contract includes a specific interface. * @notice This function uses less than 30,000 gas. * @param _interfaceID The interface identifier, as specified in ERC-165. * @return True if _interfaceID is supported, false otherwise. */ function supportsInterface( bytes4 _interfaceID ) external view returns (bool); } /** * @dev Implementation of standard for detect smart contract interfaces. */ contract SupportsInterface is ERC165 { mapping(bytes4 => bool) internal supportedInterfaces; /** * @dev Contract constructor. */ constructor() public { supportedInterfaces[0x01ffc9a7] = true; // ERC165 } /** * @dev Function to check which interfaces are suported by this contract. * @param _interfaceID Id of the interface. * @return True if _interfaceID is supported, false otherwise. */ function supportsInterface( bytes4 _interfaceID ) external override view returns (bool) { return supportedInterfaces[_interfaceID]; } } /** * @dev Utility library of inline functions on addresses. */ library AddressUtils { /** * @dev Returns whether the target address is a contract. * @param _addr Address to check. * @return addressCheck True if _addr is a contract, false if not. */ function isContract( address _addr ) internal view returns (bool addressCheck) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(_addr) } // solhint-disable-line addressCheck = (codehash != 0x0 && codehash != accountHash); } } /** * @dev Implementation of ERC-721 non-fungible token standard. */ contract NFToken is ERC721, SupportsInterface { using SafeMath for uint256; using AddressUtils for address; string constant ZERO_ADDRESS = "003001"; string constant NOT_VALID_NFT = "003002"; string constant NOT_OWNER_OR_OPERATOR = "003003"; string constant NOT_OWNER_APPROWED_OR_OPERATOR = "003004"; string constant NOT_ABLE_TO_RECEIVE_NFT = "003005"; string constant NFT_ALREADY_EXISTS = "003006"; string constant NOT_OWNER = "003007"; string constant IS_OWNER = "003008"; /** * @dev Magic value of a smart contract that can recieve NFT. * Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")). */ bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02; /** * @dev A mapping from NFT ID to the address that owns it. */ mapping (uint256 => address) internal idToOwner; /** * @dev Mapping from NFT ID to approved address. */ mapping (uint256 => address) internal idToApproval; /** * @dev Mapping from owner address to count of his tokens. */ mapping (address => uint256) private ownerToNFTokenCount; /** * @dev Mapping from owner address to mapping of operator addresses. */ mapping (address => mapping (address => bool)) internal ownerToOperators; // /** // * @dev 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. // * @param _from Sender of NFT (if address is zero address it indicates token creation). // * @param _to Receiver of NFT (if address is zero address it indicates token destruction). // * @param _tokenId The NFT that got transfered. // */ // 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. // * @param _owner Owner of NFT. // * @param _approved Address that we are approving. // * @param _tokenId NFT which we are approving. // */ // 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. // * @param _owner Owner of NFT. // * @param _operator Address to which we are setting operator rights. // * @param _approved Status of operator rights(true if operator rights are given and false if // * revoked). // */ // event ApprovalForAll( // address indexed _owner, // address indexed _operator, // bool _approved // ); /** * @dev Guarantees that the msg.sender is an owner or operator of the given NFT. * @param _tokenId ID of the NFT to validate. */ modifier canOperate( uint256 _tokenId ) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender], NOT_OWNER_OR_OPERATOR); _; } /** * @dev Guarantees that the msg.sender is allowed to transfer NFT. * @param _tokenId ID of the NFT to transfer. */ modifier canTransfer( uint256 _tokenId ) { address tokenOwner = idToOwner[_tokenId]; require( tokenOwner == msg.sender || idToApproval[_tokenId] == msg.sender || ownerToOperators[tokenOwner][msg.sender], NOT_OWNER_APPROWED_OR_OPERATOR ); _; } /** * @dev Guarantees that _tokenId is a valid Token. * @param _tokenId ID of the NFT to validate. */ modifier validNFToken( uint256 _tokenId ) { require(idToOwner[_tokenId] != address(0), NOT_VALID_NFT); _; } /** * @dev Contract constructor. */ constructor() public { supportedInterfaces[0x80ac58cd] = true; // ERC721 } /** * @dev Transfers the ownership of an NFT from one address to another address. This function can * be changed to payable. * @notice 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. 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,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 calldata _data ) external override { _safeTransferFrom(_from, _to, _tokenId, _data); } /** * @dev Transfers the ownership of an NFT from one address to another address. This function can * be changed to payable. * @notice 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 override { _safeTransferFrom(_from, _to, _tokenId, ""); } /** * @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. This function can be changed to payable. * @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else * they maybe be permanently lost. * @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 ) external override canTransfer(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from, NOT_OWNER); require(_to != address(0), ZERO_ADDRESS); _transfer(_to, _tokenId); } /** * @dev Set or reaffirm the approved address for an NFT. This function can be changed to payable. * @notice 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 Address to be approved for the given NFT ID. * @param _tokenId ID of the token to be approved. */ function approve( address _approved, uint256 _tokenId ) external override canOperate(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(_approved != tokenOwner, IS_OWNER); idToApproval[_tokenId] = _approved; emit Approval(tokenOwner, _approved, _tokenId); } /** * @dev Enables or disables approval for a third party ("operator") to manage all of * `msg.sender`'s assets. It also emits the ApprovalForAll event. * @notice This works even if sender doesn't own any tokens at the time. * @param _operator Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval. */ function setApprovalForAll( address _operator, bool _approved ) external override { ownerToOperators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are * considered invalid, and this function throws for queries about the zero address. * @param _owner Address for whom to query the balance. * @return Balance of _owner. */ function balanceOf( address _owner ) external override view returns (uint256) { require(_owner != address(0), ZERO_ADDRESS); return _getOwnerNFTCount(_owner); } /** * @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered * invalid, and queries about them do throw. * @param _tokenId The identifier for an NFT. * @return _owner Address of _tokenId owner. */ function ownerOf( uint256 _tokenId ) external override view returns (address _owner) { _owner = idToOwner[_tokenId]; require(_owner != address(0), NOT_VALID_NFT); } /** * @dev Get the approved address for a single NFT. * @notice Throws if `_tokenId` is not a valid NFT. * @param _tokenId ID of the NFT to query the approval of. * @return Address that _tokenId is approved for. */ function getApproved( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (address) { return idToApproval[_tokenId]; } /** * @dev Checks if `_operator` is an approved operator for `_owner`. * @param _owner The address that owns the NFTs. * @param _operator The address that acts on behalf of the owner. * @return True if approved for all, false otherwise. */ function isApprovedForAll( address _owner, address _operator ) external override view returns (bool) { return ownerToOperators[_owner][_operator]; } /** * @dev Actually preforms the transfer. * @notice Does NO checks. * @param _to Address of a new owner. * @param _tokenId The NFT that is being transferred. */ function _transfer( address _to, uint256 _tokenId ) internal { address from = idToOwner[_tokenId]; _clearApproval(_tokenId); _removeNFToken(from, _tokenId); _addNFToken(_to, _tokenId); emit Transfer(from, _to, _tokenId); } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal virtual { require(_to != address(0), ZERO_ADDRESS); require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); _addNFToken(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external burn * function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal virtual validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; _clearApproval(_tokenId); _removeNFToken(tokenOwner, _tokenId); emit Transfer(tokenOwner, address(0), _tokenId); } /** * @dev Removes a NFT from owner. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); ownerToNFTokenCount[_from] = ownerToNFTokenCount[_from] - 1; delete idToOwner[_tokenId]; } /** * @dev Assignes a new NFT to owner. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToNFTokenCount[_to] = ownerToNFTokenCount[_to].add(1); } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage (gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal virtual view returns (uint256) { return ownerToNFTokenCount[_owner]; } /** * @dev Actually perform the safeTransferFrom. * @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 memory _data ) private canTransfer(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from, NOT_OWNER); require(_to != address(0), ZERO_ADDRESS); _transfer(_to, _tokenId); if (_to.isContract()) { bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data); require(retval == MAGIC_ON_ERC721_RECEIVED, NOT_ABLE_TO_RECEIVE_NFT); } } /** * @dev Clears the current approval of a given NFT ID. * @param _tokenId ID of the NFT to be transferred. */ function _clearApproval( uint256 _tokenId ) private { if (idToApproval[_tokenId] != address(0)) { delete idToApproval[_tokenId]; } } } /** * @dev Optional metadata extension for ERC-721 non-fungible token standard. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md. */ interface ERC721Metadata { /** * @dev Returns a descriptive name for a collection of NFTs in this contract. * @return _name Representing name. */ function name() external view returns (string memory _name); /** * @dev Returns a abbreviated name for a collection of NFTs in this contract. * @return _symbol Representing symbol. */ function symbol() external view returns (string memory _symbol); /** * @dev Returns a distinct Uniform Resource Identifier (URI) for a given asset. It Throws if * `_tokenId` is not a valid NFT. URIs are defined in RFC3986. The URI may point to a JSON file * that conforms to the "ERC721 Metadata JSON Schema". * @return URI of _tokenId. */ function tokenURI(uint256 _tokenId) external view returns (string memory); } /** * @dev Optional metadata implementation for ERC-721 non-fungible token standard. */ contract NFTokenMetadata is NFToken, ERC721Metadata { /** * @dev A descriptive name for a collection of NFTs. */ string internal nftName; /** * @dev An abbreviated name for NFTokens. */ string internal nftSymbol; /** * @dev Mapping from NFT ID to metadata uri. */ mapping (uint256 => string) internal idToUri; /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftName and nftSymbol. */ constructor() public { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata } /** * @dev Returns a descriptive name for a collection of NFTokens. * @return _name Representing name. */ function name() external override view returns (string memory _name) { _name = nftName; } /** * @dev Returns an abbreviated name for NFTokens. * @return _symbol Representing symbol. */ function symbol() external override view returns (string memory _symbol) { _symbol = nftSymbol; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory) { return idToUri[_tokenId]; } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } } /** * @dev Set a distinct URI (RFC 3986) for a given NFT ID. * @notice This is an internal function which should be called from user-implemented external * function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId Id for which we want URI. * @param _uri String representing RFC 3986 URI. */ function _setTokenUri( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToUri[_tokenId] = _uri; } } /** * @dev Optional enumeration extension for ERC-721 non-fungible token standard. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md. */ interface ERC721Enumerable { /** * @dev Returns a count of valid NFTs tracked by this contract, where each one of them has an * assigned and queryable owner not equal to the zero address. * @return Total supply of NFTs. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token identifier for the `_index`th NFT. Sort order is not specified. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external view returns (uint256); /** * @dev Returns the token identifier for the `_index`th NFT assigned to `_owner`. Sort order is * not specified. It throws if `_index` >= `balanceOf(_owner)` or if `_owner` is the zero address, * representing invalid NFTs. * @param _owner An address where we are interested in NFTs owned by them. * @param _index A counter less than `balanceOf(_owner)`. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external view returns (uint256); } /** * @dev Optional enumeration implementation for ERC-721 non-fungible token standard. */ contract NFTokenEnumerable is NFToken, ERC721Enumerable { string constant INVALID_INDEX = "005007"; /** * @dev Array of all NFT IDs. */ uint256[] internal tokens; /** * @dev Mapping from token ID to its index in global tokens array. */ mapping(uint256 => uint256) internal idToIndex; /** * @dev Mapping from owner to list of owned NFT IDs. */ mapping(address => uint256[]) internal ownerToIds; /** * @dev Mapping from NFT ID to its index in the owner tokens list. */ mapping(uint256 => uint256) internal idToOwnerIndex; /** * @dev Contract constructor. */ constructor() public { supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable } /** * @dev Returns the count of all existing NFTokens. * @return Total supply of NFTs. */ function totalSupply() external override view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external override view returns (uint256) { require(_index < tokens.length, INVALID_INDEX); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external override view returns (uint256) { require(_index < ownerToIds[_owner].length, INVALID_INDEX); return ownerToIds[_owner][_index]; } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal override virtual { super._mint(_to, _tokenId); tokens.push(_tokenId); idToIndex[_tokenId] = tokens.length - 1; } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); uint256 tokenIndex = idToIndex[_tokenId]; uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.pop(); // This wastes gas if you are burning the last token but saves a little gas if you are not. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); } /** * @dev Assignes a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1; } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal override virtual view returns (uint256) { return ownerToIds[_owner].length; } } /** * @dev The contract has an owner address, and provides basic authorization control which * simplifies the implementation of user permissions. */ contract Ownable { /** * @dev Error constants. */ string public constant NOT_CURRENT_OWNER = "018001"; string public constant CANNOT_TRANSFER_TO_ZERO_ADDRESS = "018002"; /** * @dev Current owner address. */ address public owner; /** * @dev An event which is triggered when the owner is changed. * @param previousOwner The address of the previous owner. * @param newOwner The address of the new owner. */ event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The 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, NOT_CURRENT_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), CANNOT_TRANSFER_TO_ZERO_ADDRESS); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } interface IMintable { function mintFor( address to, uint256 id, bytes calldata blueprint ) external; } library Bytes { /** * @dev Converts a `uint256` to a `string`. * via OraclizeAPI - MIT licence * https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol */ function fromUint(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + (temp % 10))); temp /= 10; } return string(buffer); } bytes constant alphabet = "0123456789abcdef"; /** * Index Of * * Locates and returns the position of a character within a string starting * from a defined offset * * @param _base When being used for a data type this is the extended object * otherwise this is the string acting as the haystack to be * searched * @param _value The needle to search for, at present this is currently * limited to one character * @param _offset The starting point to start searching from which can start * from 0, but must not exceed the length of the string * @return int The position of the needle starting from 0 and returning -1 * in the case of no matches found */ function indexOf( bytes memory _base, string memory _value, uint256 _offset ) internal pure returns (int256) { bytes memory _valueBytes = bytes(_value); assert(_valueBytes.length == 1); for (uint256 i = _offset; i < _base.length; i++) { if (_base[i] == _valueBytes[0]) { return int256(i); } } return -1; } function substring( bytes memory strBytes, uint256 startIndex, uint256 endIndex ) internal pure returns (string memory) { bytes memory result = new bytes(endIndex - startIndex); for (uint256 i = startIndex; i < endIndex; i++) { result[i - startIndex] = strBytes[i]; } return string(result); } function toUint(bytes memory b) internal pure returns (uint256) { uint256 result = 0; for (uint256 i = 0; i < b.length; i++) { uint256 val = uint256(uint8(b[i])); if (val >= 48 && val <= 57) { result = result * 10 + (val - 48); } } return result; } } library Minting { // Split the minting blob into token_id and blueprint portions // {token_id}:{blueprint} function split(bytes calldata blob) internal pure returns (uint256, bytes memory) { int256 index = Bytes.indexOf(blob, ":", 0); require(index >= 0, "Separator must exist"); // Trim the { and } from the parameters uint256 tokenID = Bytes.toUint(blob[1:uint256(index) - 1]); uint256 blueprintLength = blob.length - uint256(index) - 3; if (blueprintLength == 0) { return (tokenID, bytes("")); } bytes calldata blueprint = blob[uint256(index) + 2:blob.length - 1]; return (tokenID, blueprint); } } abstract contract Mintable is Ownable, IMintable { address public imx; mapping(uint256 => bytes) public blueprints; event AssetMinted(address to, uint256 id, bytes blueprint); constructor(address _owner, address _imx) { imx = _imx; require(_owner != address(0), "Owner must not be empty"); transferOwnership(_owner); } modifier onlyIMX() { require(msg.sender == imx, "Function can only be called by IMX"); _; } function mintFor( address user, uint256 quantity, bytes calldata mintingBlob ) external override onlyIMX { require(quantity == 1, "Mintable: invalid quantity"); (uint256 id, bytes memory blueprint) = Minting.split(mintingBlob); _mintFor(user, id, blueprint); blueprints[id] = blueprint; emit AssetMinted(user, id, blueprint); } function _mintFor( address to, uint256 id, bytes memory blueprint ) internal virtual; } contract ArtGalleryTokenImx is NFTokenEnumerable, NFTokenMetadata, Ownable, Mintable { /** * Immutable support */ /** * @dev Contract constructor. Sets metadata extension `name` and `symbol`. * @param _imx immutable contract address */ constructor(address _imx) public Mintable(msg.sender, _imx) { nftName = "ArtGallery"; nftSymbol = "ArtGallery"; publisher = msg.sender; //publisher == owner == contract deployer _own_address = address(this); } /** * @dev mint implementation * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. * @param _uri String representing RFC 3986 URI. */ function __mint( address _to, uint256 _tokenId, string memory _uri ) internal { super._mint(_to, _tokenId); super._setTokenUri(_tokenId, _uri); } /** * @dev internal mint function to be called from mintFor called by immutable contract * @param to address that will own the minted NFT * @param id token id of the NFT to be minted. * @param blueprint bytes representing NFT uri string. */ function _mintFor( address to, uint256 id, bytes memory blueprint ) internal override { string memory uri = string(blueprint); __mint(to, id, uri); } /** * ArtGalleryToken */ address public _own_address; address publisher = 0x0000000000000000000000000000000000000000; address bankContract = 0x0000000000000000000000000000000000000000; modifier bankOrPublisher() { require( (msg.sender == publisher) || (msg.sender == bankContract && isContract(msg.sender)), "only bank or publisher can call this function" ); _; } modifier onlyPublisher() { require( msg.sender == publisher, "only publisher can call this function" ); _; } modifier onlyBankContract() { require( msg.sender == bankContract && isContract(msg.sender), "only bank can call this function" ); _; } /** * @dev not bullet-proof check, but additional measure, actually we require specific (contract) address, * which is key (see onlyBankContract) */ function isContract(address _addr) internal view returns (bool) { uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } /** * @dev only to be used if you do not have minted tokens, * i.e. what to change name& symbol for cotnract without assets * all minted tokens will disappear */ function setNFTName(string calldata new_name) external onlyOwner { nftName = new_name; } /** * @dev only to be used if you do not have minted tokens, * i.e. what to change name& symbol for cotnract without assets * all minted tokens will disappear */ function setNFTSymbol(string calldata new_symbol) external onlyOwner { nftSymbol = new_symbol; } function transferPublishRight(address newPublisher) external onlyOwner { publisher = newPublisher; } function getPublisher() public view returns (address) { return publisher; } function transferBankRight(address newBankContract) external onlyOwner { bankContract = newBankContract; } function getBankContract() public view returns (address) { return bankContract; } /** * @dev returns contract balance */ function getContractBalance() public view returns (uint256) { return address(this).balance; } /** * @dev Mints a new NFT. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. * @param _uri String representing RFC 3986 URI. */ function mint( address _to, uint256 _tokenId, string calldata _uri ) external bankOrPublisher { __mint(_to, _tokenId, _uri); } /** * @dev Removes a NFT from owner. * @param _tokenId Which NFT we want to remove. */ function burn(uint256 _tokenId) external bankOrPublisher { super._burn(_tokenId); } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint(address _to, uint256 _tokenId) internal virtual override(NFToken, NFTokenEnumerable) { NFTokenEnumerable._mint(_to, _tokenId); } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn(uint256 _tokenId) internal virtual override(NFTokenMetadata, NFTokenEnumerable) { NFTokenEnumerable._burn(_tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken(address _from, uint256 _tokenId) internal override(NFToken, NFTokenEnumerable) { NFTokenEnumerable._removeNFToken(_from, _tokenId); } /** * @dev Assigns a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken(address _to, uint256 _tokenId) internal override(NFToken, NFTokenEnumerable) { NFTokenEnumerable._addNFToken(_to, _tokenId); } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount(address _owner) internal view override(NFToken, NFTokenEnumerable) returns (uint256) { return NFTokenEnumerable._getOwnerNFTCount(_owner); } }
* @dev Assigns a new NFT to an address. @notice Use and override this function with caution. Wrong usage can have serious consequences. @param _to Address to wich we want to add the NFT. @param _tokenId Which NFT we want to add./
function _addNFToken(address _to, uint256 _tokenId) internal override(NFToken, NFTokenEnumerable) { NFTokenEnumerable._addNFToken(_to, _tokenId); }
10,392,929
[ 1, 24842, 279, 394, 423, 4464, 358, 392, 1758, 18, 225, 2672, 471, 3849, 333, 445, 598, 3474, 1421, 18, 24668, 4084, 848, 1240, 703, 22774, 356, 17190, 18, 225, 389, 869, 5267, 358, 341, 1354, 732, 2545, 358, 527, 326, 423, 4464, 18, 225, 389, 2316, 548, 21918, 423, 4464, 732, 2545, 358, 527, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 1289, 26473, 1345, 12, 2867, 389, 869, 16, 2254, 5034, 389, 2316, 548, 13, 203, 3639, 2713, 203, 3639, 3849, 12, 26473, 1345, 16, 423, 42, 1345, 3572, 25121, 13, 203, 565, 288, 203, 3639, 423, 42, 1345, 3572, 25121, 6315, 1289, 26473, 1345, 24899, 869, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.3; /* 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. © 2020 The LAO I, LLC */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract ReentrancyGuard { bool private _notEntered; constructor () internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // 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 LAO is Ownable, ReentrancyGuard { using SafeMath for uint256; /*************** GLOBAL CONSTANTS ***************/ uint256 public periodDuration; // default = 17280 = 4.8 hours in seconds (5 periods per day) uint256 public votingPeriodLength; // default = 35 periods (7 days) uint256 public gracePeriodLength; // default = 35 periods (7 days) uint256 public proposalDeposit; // default = 10 ETH (~$1,000 worth of ETH at contract deployment) uint256 public dilutionBound; // default = 3 - maximum multiplier a YES voter will be obligated to pay in case of mass ragequit uint256 public processingReward; // default = 0.1 - amount of ETH to give to whoever processes a proposal uint256 public summoningTime; // needed to determine the current period address public depositToken; // deposit token contract reference; default = wETH /****** AdminFee - LAO exclusive, add on to original Moloch *********/ uint256 constant paymentPeriod = 90 days; // 90 days - 1 day is for test only! uint256 public lastPaymentTime; // this will set as 'now' in constructor = summoningTime address public laoFundAddress; // this field MUST be set in constructor or set to default to summoner here uint256 public adminFeeDenominator = 200; // initial denominator // HARD-CODED LIMITS // These numbers are quite arbitrary; they are small enough to avoid overflows when doing calculations // with periods or shares, yet big enough to not limit reasonable use cases. uint256 constant MAX_VOTING_PERIOD_LENGTH = 10**18; // maximum length of voting period uint256 constant MAX_GRACE_PERIOD_LENGTH = 10**18; // maximum length of grace period uint256 constant MAX_DILUTION_BOUND = 10**18; // maximum dilution bound uint256 constant MAX_NUMBER_OF_SHARES_AND_LOOT = 10**18; // maximum number of shares that can be minted uint256 constant MAX_TOKEN_WHITELIST_COUNT = 200; // maximum number of whitelisted tokens, default is 400 uint256 constant MAX_TOKEN_GUILDBANK_COUNT = 100; // maximum number of tokens with non-zero balance in guildbank, default is 200 // *************** // EVENTS // *************** event SummonComplete(address indexed summoner, address[] tokens, uint256 summoningTime, uint256 periodDuration, uint256 votingPeriodLength, uint256 gracePeriodLength, uint256 proposalDeposit, uint256 dilutionBound, uint256 processingReward); event SubmitProposal(address indexed applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string details, bool[6] flags, uint256 proposalId, address indexed delegateKey, address indexed memberAddress); event SponsorProposal(address indexed delegateKey, address indexed memberAddress, uint256 proposalId, uint256 proposalIndex, uint256 startingPeriod); event SubmitVote(uint256 proposalId, uint256 indexed proposalIndex, address indexed delegateKey, address indexed memberAddress, uint8 uintVote); event ProcessProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event ProcessWhitelistProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event ProcessGuildKickProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event Ragequit(address indexed memberAddress, uint256 sharesToBurn, uint256 lootToBurn); event TokensCollected(address indexed token, uint256 amountToCollect); event CancelProposal(uint256 indexed proposalId, address applicantAddress); event UpdateDelegateKey(address indexed memberAddress, address newDelegateKey); event Withdraw(address indexed memberAddress, address token, uint256 amount); // ******************* // INTERNAL ACCOUNTING // ******************* uint256 public proposalCount = 0; // total proposals submitted uint256 public totalShares = 0; // total shares across all members uint256 public totalLoot = 0; // total loot across all members uint256 public totalGuildBankTokens = 0; // total tokens with non-zero balance in guild bank address public constant GUILD = address(0xdead); address public constant ESCROW = address(0xbeef); address public constant TOTAL = address(0xbabe); mapping (address => mapping(address => uint256)) public userTokenBalances; // userTokenBalances[userAddress][tokenAddress] enum Vote { Null, // default value, counted as abstention Yes, No } struct Member { address delegateKey; // the key responsible for submitting proposals and voting - defaults to member address unless updated uint256 shares; // the # of voting shares assigned to this member uint256 loot; // the loot amount available to this member (combined with shares on ragequit) bool exists; // always true once a member has been created uint256 highestIndexYesVote; // highest proposal index # on which the member voted YES uint256 jailed; // set to proposalIndex of a passing guild kick proposal for this member, prevents voting on and sponsoring proposals } struct Proposal { address applicant; // the applicant who wishes to become a member - this key will be used for withdrawals (doubles as guild kick target for gkick proposals) address proposer; // the account that submitted the proposal (can be non-member) address sponsor; // the member that sponsored the proposal (moving it into the queue) uint256 sharesRequested; // the # of shares the applicant is requesting uint256 lootRequested; // the amount of loot the applicant is requesting uint256 tributeOffered; // amount of tokens offered as tribute address tributeToken; // tribute token contract reference uint256 paymentRequested; // amount of tokens requested as payment address paymentToken; // payment token contract reference uint256 startingPeriod; // the period in which voting can start for this proposal uint256 yesVotes; // the total number of YES votes for this proposal uint256 noVotes; // the total number of NO votes for this proposal bool[6] flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] string details; // proposal details - could be IPFS hash, plaintext, or JSON uint256 maxTotalSharesAndLootAtYesVote; // the maximum # of total shares encountered at a yes vote on this proposal mapping(address => Vote) votesByMember; // the votes on this proposal by each member } mapping(address => bool) public tokenWhitelist; address[] public approvedTokens; mapping(address => bool) public proposedToWhitelist; mapping(address => bool) public proposedToKick; mapping(address => Member) public members; mapping(address => address) public memberAddressByDelegateKey; mapping(uint256 => Proposal) public proposals; uint256[] public proposalQueue; modifier onlyMember { require(members[msg.sender].shares > 0 || members[msg.sender].loot > 0, "not a member"); _; } modifier onlyShareholder { require(members[msg.sender].shares > 0, "not a shareholder"); _; } modifier onlyDelegate { require(members[memberAddressByDelegateKey[msg.sender]].shares > 0, "not a delegate"); _; } constructor( address _summoner, address[] memory _approvedTokens, uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _proposalDeposit, uint256 _dilutionBound, uint256 _processingReward, address _laoFundAddress ) public { require(_summoner != address(0), "summoner cannot be 0"); require(_periodDuration > 0, "_periodDuration cannot be 0"); require(_votingPeriodLength > 0, "_votingPeriodLength cannot be 0"); require(_votingPeriodLength <= MAX_VOTING_PERIOD_LENGTH, "_votingPeriodLength exceeds limit"); require(_gracePeriodLength <= MAX_GRACE_PERIOD_LENGTH, "_gracePeriodLength exceeds limit"); require(_dilutionBound > 0, "_dilutionBound cannot be 0"); require(_dilutionBound <= MAX_DILUTION_BOUND, "_dilutionBound exceeds limit"); require(_approvedTokens.length > 0, "need at least one approved token"); require(_approvedTokens.length <= MAX_TOKEN_WHITELIST_COUNT, "too many tokens"); require(_proposalDeposit >= _processingReward, "_proposalDeposit cannot be smaller than _processingReward"); require(_laoFundAddress != address(0), "laoFundAddress cannot be 0"); depositToken = _approvedTokens[0]; // NOTE: move event up here, avoid stack too deep if too many approved tokens emit SummonComplete(_summoner, _approvedTokens, now, _periodDuration, _votingPeriodLength, _gracePeriodLength, _proposalDeposit, _dilutionBound, _processingReward); for (uint256 i = 0; i < _approvedTokens.length; i++) { require(_approvedTokens[i] != address(0), "_approvedToken cannot be 0"); require(!tokenWhitelist[_approvedTokens[i]], "duplicate approved token"); tokenWhitelist[_approvedTokens[i]] = true; approvedTokens.push(_approvedTokens[i]); } periodDuration = _periodDuration; votingPeriodLength = _votingPeriodLength; gracePeriodLength = _gracePeriodLength; proposalDeposit = _proposalDeposit; dilutionBound = _dilutionBound; processingReward = _processingReward; summoningTime = now; laoFundAddress = _laoFundAddress; // LAO add on for adminFee lastPaymentTime = now; // LAO add on for adminFee members[_summoner] = Member(_summoner, 1, 0, true, 0, 0); memberAddressByDelegateKey[_summoner] = _summoner; totalShares = 1; } /****************** ADMIN FEE FUNCTIONS -- LAO add on functions to MOLOCH setAdminFee can only be changed by Owner withdrawAdminFee can be called by any ETH address ******************/ // @dev Owner can change amount of adminFee and direction of funds // @param adminFeeDenominator must be >= 200. Greater than 200, will equal 0.5% or less of assets // @param laoFundAddress - where the Owner wants the funds to go function setAdminFee(uint256 _adminFeeDenominator, address _laoFundAddress) public nonReentrant onlyOwner{ require(_adminFeeDenominator >= 200); adminFeeDenominator = _adminFeeDenominator; laoFundAddress = _laoFundAddress; } function withdrawAdminFee() public nonReentrant { require(now >= lastPaymentTime.add(paymentPeriod), "90 days have not passed since last withdrawal"); lastPaymentTime = lastPaymentTime.add(paymentPeriod); // set it to the next payment period // local variables to save gas by reading from storage only 1x uint256 denominator = adminFeeDenominator; address recipient = laoFundAddress; for (uint256 i = 0; i < approvedTokens.length; i++) { address token = approvedTokens[i]; uint256 amount = userTokenBalances[GUILD][token] / denominator; if (amount > 0) { // otherwise skip for efficiency, only tokens with a balance userTokenBalances[GUILD][token] -= amount; userTokenBalances[recipient][token] += amount; } } } /***************** PROPOSAL FUNCTIONS *****************/ function submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string memory details ) public nonReentrant returns (uint256 proposalId) { require(sharesRequested.add(lootRequested) <= MAX_NUMBER_OF_SHARES_AND_LOOT, "too many shares requested"); require(tokenWhitelist[tributeToken], "tributeToken is not whitelisted"); require(tokenWhitelist[paymentToken], "payment is not whitelisted"); require(applicant != address(0), "applicant cannot be 0"); require(applicant != GUILD && applicant != ESCROW && applicant != TOTAL, "applicant address cannot be reserved"); require(members[applicant].jailed == 0, "proposal applicant must not be jailed"); if (tributeOffered > 0 && userTokenBalances[GUILD][tributeToken] == 0) { require(totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, 'cannot submit more tribute proposals for new tokens - guildbank is full'); } // collect tribute from proposer and store it in the LAO until the proposal is processed require(IERC20(tributeToken).transferFrom(msg.sender, address(this), tributeOffered), "tribute token transfer failed"); unsafeAddToBalance(ESCROW, tributeToken, tributeOffered); bool[6] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] _submitProposal(applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags); return proposalCount - 1; // return proposalId - contracts calling submit might want it } function submitWhitelistProposal(address tokenToWhitelist, string memory details) public nonReentrant returns (uint256 proposalId) { require(tokenToWhitelist != address(0), "must provide token address"); require(!tokenWhitelist[tokenToWhitelist], "cannot already have whitelisted the token"); require(approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "cannot submit more whitelist proposals"); bool[6] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] flags[4] = true; // whitelist _submitProposal(address(0), 0, 0, 0, tokenToWhitelist, 0, address(0), details, flags); return proposalCount - 1; } function submitGuildKickProposal(address memberToKick, string memory details) public nonReentrant returns (uint256 proposalId) { Member memory member = members[memberToKick]; require(member.shares > 0 || member.loot > 0, "member must have at least one share or one loot"); require(members[memberToKick].jailed == 0, "member must not already be jailed"); bool[6] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] flags[5] = true; // guild kick _submitProposal(memberToKick, 0, 0, 0, address(0), 0, address(0), details, flags); return proposalCount - 1; } function _submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string memory details, bool[6] memory flags ) internal { Proposal memory proposal = Proposal({ applicant : applicant, proposer : msg.sender, sponsor : address(0), sharesRequested : sharesRequested, lootRequested : lootRequested, tributeOffered : tributeOffered, tributeToken : tributeToken, paymentRequested : paymentRequested, paymentToken : paymentToken, startingPeriod : 0, yesVotes : 0, noVotes : 0, flags : flags, details : details, maxTotalSharesAndLootAtYesVote : 0 }); proposals[proposalCount] = proposal; address memberAddress = memberAddressByDelegateKey[msg.sender]; // NOTE: argument order matters, avoid stack too deep emit SubmitProposal(applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags, proposalCount, msg.sender, memberAddress); proposalCount += 1; } function sponsorProposal(uint256 proposalId) public nonReentrant onlyDelegate { // collect proposal deposit from sponsor and store it in the LAO until the proposal is processed require(IERC20(depositToken).transferFrom(msg.sender, address(this), proposalDeposit), "proposal deposit token transfer failed"); unsafeAddToBalance(ESCROW, depositToken, proposalDeposit); Proposal storage proposal = proposals[proposalId]; require(proposal.proposer != address(0), 'proposal must have been proposed'); require(!proposal.flags[0], "proposal has already been sponsored"); require(!proposal.flags[3], "proposal has been cancelled"); require(members[proposal.applicant].jailed == 0, "proposal applicant must not be jailed"); if (proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0) { require(totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, 'cannot sponsor more tribute proposals for new tokens - guildbank is full'); } // whitelist proposal if (proposal.flags[4]) { require(!tokenWhitelist[address(proposal.tributeToken)], "cannot already have whitelisted the token"); require(!proposedToWhitelist[address(proposal.tributeToken)], 'already proposed to whitelist'); require(approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "cannot sponsor more whitelist proposals"); proposedToWhitelist[address(proposal.tributeToken)] = true; // guild kick proposal } else if (proposal.flags[5]) { require(!proposedToKick[proposal.applicant], 'already proposed to kick'); proposedToKick[proposal.applicant] = true; } // compute startingPeriod for proposal uint256 startingPeriod = max( getCurrentPeriod(), proposalQueue.length == 0 ? 0 : proposals[proposalQueue[proposalQueue.length.sub(1)]].startingPeriod ).add(1); proposal.startingPeriod = startingPeriod; address memberAddress = memberAddressByDelegateKey[msg.sender]; proposal.sponsor = memberAddress; proposal.flags[0] = true; // sponsored // append proposal to the queue proposalQueue.push(proposalId); emit SponsorProposal(msg.sender, memberAddress, proposalId, proposalQueue.length.sub(1), startingPeriod); } // NOTE: In MolochV2/LAO proposalIndex !== proposalId function submitVote(uint256 proposalIndex, uint8 uintVote) public nonReentrant onlyDelegate { address memberAddress = memberAddressByDelegateKey[msg.sender]; Member storage member = members[memberAddress]; require(proposalIndex < proposalQueue.length, "proposal does not exist"); Proposal storage proposal = proposals[proposalQueue[proposalIndex]]; require(uintVote < 3, "must be less than 3"); Vote vote = Vote(uintVote); require(getCurrentPeriod() >= proposal.startingPeriod, "voting period has not started"); require(!hasVotingPeriodExpired(proposal.startingPeriod), "proposal voting period has expired"); require(proposal.votesByMember[memberAddress] == Vote.Null, "member has already voted"); require(vote == Vote.Yes || vote == Vote.No, "vote must be either Yes or No"); proposal.votesByMember[memberAddress] = vote; if (vote == Vote.Yes) { proposal.yesVotes = proposal.yesVotes.add(member.shares); // set highest index (latest) yes vote - must be processed for member to ragequit if (proposalIndex > member.highestIndexYesVote) { member.highestIndexYesVote = proposalIndex; } // set maximum of total shares encountered at a yes vote - used to bound dilution for yes voters if (totalShares.add(totalLoot) > proposal.maxTotalSharesAndLootAtYesVote) { proposal.maxTotalSharesAndLootAtYesVote = totalShares.add(totalLoot); } } else if (vote == Vote.No) { proposal.noVotes = proposal.noVotes.add(member.shares); } // NOTE: subgraph indexes by proposalId not proposalIndex since proposalIndex isn't set untill it's been sponsored but proposal is created on submission emit SubmitVote(proposalQueue[proposalIndex], proposalIndex, msg.sender, memberAddress, uintVote); } function processProposal(uint256 proposalIndex) public nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(!proposal.flags[4] && !proposal.flags[5], "must be a standard proposal"); proposal.flags[1] = true; // processed bool didPass = _didPass(proposalIndex); // Make the proposal fail if the new total number of shares and loot exceeds the limit if (totalShares.add(totalLoot).add(proposal.sharesRequested).add(proposal.lootRequested) > MAX_NUMBER_OF_SHARES_AND_LOOT) { didPass = false; } // Make the proposal fail if it is requesting more tokens as payment than the available guild bank balance if (proposal.paymentRequested > userTokenBalances[GUILD][proposal.paymentToken]) { didPass = false; } // Make the proposal fail if it would result in too many tokens with non-zero balance in guild bank if (proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0 && totalGuildBankTokens >= MAX_TOKEN_GUILDBANK_COUNT) { didPass = false; } // PROPOSAL PASSED if (didPass) { proposal.flags[2] = true; // didPass // if the applicant is already a member, add to their existing shares & loot if (members[proposal.applicant].exists) { members[proposal.applicant].shares = members[proposal.applicant].shares.add(proposal.sharesRequested); members[proposal.applicant].loot = members[proposal.applicant].loot.add(proposal.lootRequested); // the applicant is a new member, create a new record for them } else { // if the applicant address is already taken by a member's delegateKey, reset it to their member address if (members[memberAddressByDelegateKey[proposal.applicant]].exists) { address memberToOverride = memberAddressByDelegateKey[proposal.applicant]; memberAddressByDelegateKey[memberToOverride] = memberToOverride; members[memberToOverride].delegateKey = memberToOverride; } // use applicant address as delegateKey by default members[proposal.applicant] = Member(proposal.applicant, proposal.sharesRequested, proposal.lootRequested, true, 0, 0); memberAddressByDelegateKey[proposal.applicant] = proposal.applicant; } // mint new shares & loot totalShares = totalShares.add(proposal.sharesRequested); totalLoot = totalLoot.add(proposal.lootRequested); // if the proposal tribute is the first tokens of its kind to make it into the guild bank, increment total guild bank tokens if (userTokenBalances[GUILD][proposal.tributeToken] == 0 && proposal.tributeOffered > 0) { totalGuildBankTokens += 1; } unsafeInternalTransfer(ESCROW, GUILD, proposal.tributeToken, proposal.tributeOffered); unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposal.paymentRequested); // if the proposal spends 100% of guild bank balance for a token, decrement total guild bank tokens if (userTokenBalances[GUILD][proposal.paymentToken] == 0 && proposal.paymentRequested > 0) { totalGuildBankTokens -= 1; } // PROPOSAL FAILED } else { // return all tokens to the proposer (not the applicant, because funds come from proposer) unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered); } _returnDeposit(proposal.sponsor); emit ProcessProposal(proposalIndex, proposalId, didPass); } function processWhitelistProposal(uint256 proposalIndex) public nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(proposal.flags[4], "must be a whitelist proposal"); proposal.flags[1] = true; // processed bool didPass = _didPass(proposalIndex); if (approvedTokens.length >= MAX_TOKEN_WHITELIST_COUNT) { didPass = false; } if (didPass) { proposal.flags[2] = true; // didPass tokenWhitelist[address(proposal.tributeToken)] = true; approvedTokens.push(proposal.tributeToken); } proposedToWhitelist[address(proposal.tributeToken)] = false; _returnDeposit(proposal.sponsor); emit ProcessWhitelistProposal(proposalIndex, proposalId, didPass); } function processGuildKickProposal(uint256 proposalIndex) public nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(proposal.flags[5], "must be a guild kick proposal"); proposal.flags[1] = true; // processed bool didPass = _didPass(proposalIndex); if (didPass) { proposal.flags[2] = true; // didPass Member storage member = members[proposal.applicant]; member.jailed = proposalIndex; // transfer shares to loot member.loot = member.loot.add(member.shares); totalShares = totalShares.sub(member.shares); totalLoot = totalLoot.add(member.shares); member.shares = 0; // revoke all shares } proposedToKick[proposal.applicant] = false; _returnDeposit(proposal.sponsor); emit ProcessGuildKickProposal(proposalIndex, proposalId, didPass); } function _didPass(uint256 proposalIndex) internal view returns (bool didPass) { Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; didPass = proposal.yesVotes > proposal.noVotes; // Make the proposal fail if the dilutionBound is exceeded if ((totalShares.add(totalLoot)).mul(dilutionBound) < proposal.maxTotalSharesAndLootAtYesVote) { didPass = false; } // Make the proposal fail if the applicant is jailed // - for standard proposals, we don't want the applicant to get any shares/loot/payment // - for guild kick proposals, we should never be able to propose to kick a jailed member (or have two kick proposals active), so it doesn't matter if (members[proposal.applicant].jailed != 0) { didPass = false; } return didPass; } function _validateProposalForProcessing(uint256 proposalIndex) internal view { require(proposalIndex < proposalQueue.length, "proposal does not exist"); Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; require(getCurrentPeriod() >= proposal.startingPeriod.add(votingPeriodLength).add(gracePeriodLength), "proposal is not ready to be processed"); require(proposal.flags[1] == false, "proposal has already been processed"); require(proposalIndex == 0 || proposals[proposalQueue[proposalIndex.sub(1)]].flags[1], "previous proposal must be processed"); } function _returnDeposit(address sponsor) internal { unsafeInternalTransfer(ESCROW, msg.sender, depositToken, processingReward); unsafeInternalTransfer(ESCROW, sponsor, depositToken, proposalDeposit.sub(processingReward)); } function ragequit(uint256 sharesToBurn, uint256 lootToBurn) public nonReentrant onlyMember { _ragequit(msg.sender, sharesToBurn, lootToBurn); } function _ragequit(address memberAddress, uint256 sharesToBurn, uint256 lootToBurn) internal { uint256 initialTotalSharesAndLoot = totalShares.add(totalLoot); Member storage member = members[memberAddress]; require(member.shares >= sharesToBurn, "insufficient shares"); require(member.loot >= lootToBurn, "insufficient loot"); require(canRagequit(member.highestIndexYesVote), "cannot ragequit until highest index proposal member voted YES on is processed"); uint256 sharesAndLootToBurn = sharesToBurn.add(lootToBurn); // burn shares and loot member.shares = member.shares.sub(sharesToBurn); member.loot = member.loot.sub(lootToBurn); totalShares = totalShares.sub(sharesToBurn); totalLoot = totalLoot.sub(lootToBurn); for (uint256 i = 0; i < approvedTokens.length; i++) { uint256 amountToRagequit = fairShare(userTokenBalances[GUILD][approvedTokens[i]], sharesAndLootToBurn, initialTotalSharesAndLoot); if (amountToRagequit > 0) { // gas optimization to allow a higher maximum token limit // deliberately not using safemath here to keep overflows from preventing the function execution (which would break ragekicks) // if a token overflows, it is because the supply was artificially inflated to oblivion, so we probably don't care about it anyways userTokenBalances[GUILD][approvedTokens[i]] -= amountToRagequit; userTokenBalances[memberAddress][approvedTokens[i]] += amountToRagequit; } } emit Ragequit(msg.sender, sharesToBurn, lootToBurn); } function ragekick(address memberToKick) public nonReentrant { Member storage member = members[memberToKick]; require(member.jailed != 0, "member must be in jail"); require(member.loot > 0, "member must have some loot"); // note - should be impossible for jailed member to have shares require(canRagequit(member.highestIndexYesVote), "cannot ragequit until highest index proposal member voted YES on is processed"); _ragequit(memberToKick, 0, member.loot); } function withdrawBalance(address token, uint256 amount) public nonReentrant { _withdrawBalance(token, amount); } function withdrawBalances(address[] memory tokens, uint256[] memory amounts, bool max) public nonReentrant { require(tokens.length == amounts.length, "tokens and amounts arrays must be matching lengths"); for (uint256 i=0; i < tokens.length; i++) { uint256 withdrawAmount = amounts[i]; if (max) { // withdraw the maximum balance withdrawAmount = userTokenBalances[msg.sender][tokens[i]]; } _withdrawBalance(tokens[i], withdrawAmount); } } function _withdrawBalance(address token, uint256 amount) internal { require(userTokenBalances[msg.sender][token] >= amount, "insufficient balance"); unsafeSubtractFromBalance(msg.sender, token, amount); require(IERC20(token).transfer(msg.sender, amount), "transfer failed"); emit Withdraw(msg.sender, token, amount); } function collectTokens(address token) public onlyDelegate nonReentrant { uint256 amountToCollect = IERC20(token).balanceOf(address(this)).sub(userTokenBalances[TOTAL][token]); // only collect if 1) there are tokens to collect 2) token is whitelisted 3) token has non-zero balance require(amountToCollect > 0, 'no tokens to collect'); require(tokenWhitelist[token], 'token to collect must be whitelisted'); require(userTokenBalances[GUILD][token] > 0, 'token to collect must have non-zero guild bank balance'); unsafeAddToBalance(GUILD, token, amountToCollect); emit TokensCollected(token, amountToCollect); } // NOTE: requires that delegate key which sent the original proposal cancels, msg.sender == proposal.proposer function cancelProposal(uint256 proposalId) public nonReentrant { Proposal storage proposal = proposals[proposalId]; require(!proposal.flags[0], "proposal has already been sponsored"); require(!proposal.flags[3], "proposal has already been cancelled"); require(msg.sender == proposal.proposer, "solely the proposer can cancel"); proposal.flags[3] = true; // cancelled unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered); emit CancelProposal(proposalId, msg.sender); } function updateDelegateKey(address newDelegateKey) public nonReentrant onlyShareholder { require(newDelegateKey != address(0), "newDelegateKey cannot be 0"); // skip checks if member is setting the delegate key to their member address if (newDelegateKey != msg.sender) { require(!members[newDelegateKey].exists, "cannot overwrite existing members"); require(!members[memberAddressByDelegateKey[newDelegateKey]].exists, "cannot overwrite existing delegate keys"); } Member storage member = members[msg.sender]; memberAddressByDelegateKey[member.delegateKey] = address(0); memberAddressByDelegateKey[newDelegateKey] = msg.sender; member.delegateKey = newDelegateKey; emit UpdateDelegateKey(msg.sender, newDelegateKey); } // can only ragequit if the latest proposal you voted YES on has been processed function canRagequit(uint256 highestIndexYesVote) public view returns (bool) { require(highestIndexYesVote < proposalQueue.length, "proposal does not exist"); return proposals[proposalQueue[highestIndexYesVote]].flags[1]; } function hasVotingPeriodExpired(uint256 startingPeriod) public view returns (bool) { return getCurrentPeriod() >= startingPeriod.add(votingPeriodLength); } /*************** GETTER FUNCTIONS ***************/ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x >= y ? x : y; } function getCurrentPeriod() public view returns (uint256) { return now.sub(summoningTime).div(periodDuration); } function getProposalQueueLength() public view returns (uint256) { return proposalQueue.length; } function getProposalFlags(uint256 proposalId) public view returns (bool[6] memory) { return proposals[proposalId].flags; } function getUserTokenBalance(address user, address token) public view returns (uint256) { return userTokenBalances[user][token]; } function getMemberProposalVote(address memberAddress, uint256 proposalIndex) public view returns (Vote) { require(members[memberAddress].exists, "member does not exist"); require(proposalIndex < proposalQueue.length, "proposal does not exist"); return proposals[proposalQueue[proposalIndex]].votesByMember[memberAddress]; } function getTokenCount() public view returns (uint256) { return approvedTokens.length; } /*************** HELPER FUNCTIONS ***************/ function unsafeAddToBalance(address user, address token, uint256 amount) internal { userTokenBalances[user][token] += amount; userTokenBalances[TOTAL][token] += amount; } function unsafeSubtractFromBalance(address user, address token, uint256 amount) internal { userTokenBalances[user][token] -= amount; userTokenBalances[TOTAL][token] -= amount; } function unsafeInternalTransfer(address from, address to, address token, uint256 amount) internal { unsafeSubtractFromBalance(from, token, amount); unsafeAddToBalance(to, token, amount); } function fairShare(uint256 balance, uint256 shares, uint256 totalShares) internal pure returns (uint256) { require(totalShares != 0); if (balance == 0) { return 0; } uint256 prod = balance * shares; if (prod / balance == shares) { // no overflow in multiplication above? return prod / totalShares; } return (balance / totalShares) * shares; } }
HARD-CODED LIMITS These numbers are quite arbitrary; they are small enough to avoid overflows when doing calculations with periods or shares, yet big enough to not limit reasonable use cases. *************** EVENTS *************** ******************* INTERNAL ACCOUNTING *******************
contract LAO is Ownable, ReentrancyGuard { using SafeMath for uint256; GLOBAL CONSTANTS AdminFee - LAO exclusive, add on to original Moloch event SummonComplete(address indexed summoner, address[] tokens, uint256 summoningTime, uint256 periodDuration, uint256 votingPeriodLength, uint256 gracePeriodLength, uint256 proposalDeposit, uint256 dilutionBound, uint256 processingReward); event SubmitProposal(address indexed applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string details, bool[6] flags, uint256 proposalId, address indexed delegateKey, address indexed memberAddress); event SponsorProposal(address indexed delegateKey, address indexed memberAddress, uint256 proposalId, uint256 proposalIndex, uint256 startingPeriod); event SubmitVote(uint256 proposalId, uint256 indexed proposalIndex, address indexed delegateKey, address indexed memberAddress, uint8 uintVote); event ProcessProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event ProcessWhitelistProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event ProcessGuildKickProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event Ragequit(address indexed memberAddress, uint256 sharesToBurn, uint256 lootToBurn); event TokensCollected(address indexed token, uint256 amountToCollect); event CancelProposal(uint256 indexed proposalId, address applicantAddress); event UpdateDelegateKey(address indexed memberAddress, address newDelegateKey); event Withdraw(address indexed memberAddress, address token, uint256 amount); address public constant GUILD = address(0xdead); address public constant ESCROW = address(0xbeef); address public constant TOTAL = address(0xbabe); enum Vote { Yes, No } struct Member { } struct Proposal { } mapping(address => bool) public tokenWhitelist; address[] public approvedTokens; mapping(address => bool) public proposedToWhitelist; mapping(address => bool) public proposedToKick; mapping(address => Member) public members; mapping(address => address) public memberAddressByDelegateKey; mapping(uint256 => Proposal) public proposals; uint256[] public proposalQueue; modifier onlyMember { require(members[msg.sender].shares > 0 || members[msg.sender].loot > 0, "not a member"); _; } modifier onlyShareholder { require(members[msg.sender].shares > 0, "not a shareholder"); _; } modifier onlyDelegate { require(members[memberAddressByDelegateKey[msg.sender]].shares > 0, "not a delegate"); _; } constructor( address _summoner, address[] memory _approvedTokens, uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _proposalDeposit, uint256 _dilutionBound, uint256 _processingReward, address _laoFundAddress ) public { require(_summoner != address(0), "summoner cannot be 0"); require(_periodDuration > 0, "_periodDuration cannot be 0"); require(_votingPeriodLength > 0, "_votingPeriodLength cannot be 0"); require(_votingPeriodLength <= MAX_VOTING_PERIOD_LENGTH, "_votingPeriodLength exceeds limit"); require(_gracePeriodLength <= MAX_GRACE_PERIOD_LENGTH, "_gracePeriodLength exceeds limit"); require(_dilutionBound > 0, "_dilutionBound cannot be 0"); require(_dilutionBound <= MAX_DILUTION_BOUND, "_dilutionBound exceeds limit"); require(_approvedTokens.length > 0, "need at least one approved token"); require(_approvedTokens.length <= MAX_TOKEN_WHITELIST_COUNT, "too many tokens"); require(_proposalDeposit >= _processingReward, "_proposalDeposit cannot be smaller than _processingReward"); require(_laoFundAddress != address(0), "laoFundAddress cannot be 0"); depositToken = _approvedTokens[0]; emit SummonComplete(_summoner, _approvedTokens, now, _periodDuration, _votingPeriodLength, _gracePeriodLength, _proposalDeposit, _dilutionBound, _processingReward); for (uint256 i = 0; i < _approvedTokens.length; i++) { require(_approvedTokens[i] != address(0), "_approvedToken cannot be 0"); require(!tokenWhitelist[_approvedTokens[i]], "duplicate approved token"); tokenWhitelist[_approvedTokens[i]] = true; approvedTokens.push(_approvedTokens[i]); } periodDuration = _periodDuration; votingPeriodLength = _votingPeriodLength; gracePeriodLength = _gracePeriodLength; proposalDeposit = _proposalDeposit; dilutionBound = _dilutionBound; processingReward = _processingReward; summoningTime = now; members[_summoner] = Member(_summoner, 1, 0, true, 0, 0); memberAddressByDelegateKey[_summoner] = _summoner; totalShares = 1; } ) public { require(_summoner != address(0), "summoner cannot be 0"); require(_periodDuration > 0, "_periodDuration cannot be 0"); require(_votingPeriodLength > 0, "_votingPeriodLength cannot be 0"); require(_votingPeriodLength <= MAX_VOTING_PERIOD_LENGTH, "_votingPeriodLength exceeds limit"); require(_gracePeriodLength <= MAX_GRACE_PERIOD_LENGTH, "_gracePeriodLength exceeds limit"); require(_dilutionBound > 0, "_dilutionBound cannot be 0"); require(_dilutionBound <= MAX_DILUTION_BOUND, "_dilutionBound exceeds limit"); require(_approvedTokens.length > 0, "need at least one approved token"); require(_approvedTokens.length <= MAX_TOKEN_WHITELIST_COUNT, "too many tokens"); require(_proposalDeposit >= _processingReward, "_proposalDeposit cannot be smaller than _processingReward"); require(_laoFundAddress != address(0), "laoFundAddress cannot be 0"); depositToken = _approvedTokens[0]; emit SummonComplete(_summoner, _approvedTokens, now, _periodDuration, _votingPeriodLength, _gracePeriodLength, _proposalDeposit, _dilutionBound, _processingReward); for (uint256 i = 0; i < _approvedTokens.length; i++) { require(_approvedTokens[i] != address(0), "_approvedToken cannot be 0"); require(!tokenWhitelist[_approvedTokens[i]], "duplicate approved token"); tokenWhitelist[_approvedTokens[i]] = true; approvedTokens.push(_approvedTokens[i]); } periodDuration = _periodDuration; votingPeriodLength = _votingPeriodLength; gracePeriodLength = _gracePeriodLength; proposalDeposit = _proposalDeposit; dilutionBound = _dilutionBound; processingReward = _processingReward; summoningTime = now; members[_summoner] = Member(_summoner, 1, 0, true, 0, 0); memberAddressByDelegateKey[_summoner] = _summoner; totalShares = 1; } ADMIN FEE FUNCTIONS -- LAO add on functions to MOLOCH setAdminFee can only be changed by Owner withdrawAdminFee can be called by any ETH address function setAdminFee(uint256 _adminFeeDenominator, address _laoFundAddress) public nonReentrant onlyOwner{ require(_adminFeeDenominator >= 200); adminFeeDenominator = _adminFeeDenominator; laoFundAddress = _laoFundAddress; } function withdrawAdminFee() public nonReentrant { require(now >= lastPaymentTime.add(paymentPeriod), "90 days have not passed since last withdrawal"); uint256 denominator = adminFeeDenominator; address recipient = laoFundAddress; for (uint256 i = 0; i < approvedTokens.length; i++) { address token = approvedTokens[i]; uint256 amount = userTokenBalances[GUILD][token] / denominator; userTokenBalances[GUILD][token] -= amount; userTokenBalances[recipient][token] += amount; } } function withdrawAdminFee() public nonReentrant { require(now >= lastPaymentTime.add(paymentPeriod), "90 days have not passed since last withdrawal"); uint256 denominator = adminFeeDenominator; address recipient = laoFundAddress; for (uint256 i = 0; i < approvedTokens.length; i++) { address token = approvedTokens[i]; uint256 amount = userTokenBalances[GUILD][token] / denominator; userTokenBalances[GUILD][token] -= amount; userTokenBalances[recipient][token] += amount; } } }
10,726,452
[ 1, 44, 8085, 17, 9086, 2056, 13052, 10158, 8646, 5600, 854, 25102, 11078, 31, 2898, 854, 5264, 7304, 358, 4543, 9391, 87, 1347, 9957, 20882, 598, 12777, 578, 24123, 16, 4671, 5446, 7304, 358, 486, 1800, 23589, 999, 6088, 18, 225, 9964, 55, 282, 18139, 29437, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2928, 51, 353, 14223, 6914, 16, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 7779, 24023, 55, 203, 203, 377, 7807, 14667, 300, 2928, 51, 12060, 16, 527, 603, 358, 2282, 490, 355, 9842, 203, 27699, 203, 565, 871, 9352, 2586, 6322, 12, 2867, 8808, 2142, 2586, 264, 16, 1758, 8526, 2430, 16, 2254, 5034, 2142, 2586, 310, 950, 16, 2254, 5034, 3879, 5326, 16, 2254, 5034, 331, 17128, 5027, 1782, 16, 2254, 5034, 13658, 5027, 1782, 16, 2254, 5034, 14708, 758, 1724, 16, 2254, 5034, 302, 330, 1421, 3499, 16, 2254, 5034, 4929, 17631, 1060, 1769, 203, 565, 871, 17320, 14592, 12, 2867, 8808, 513, 1780, 970, 16, 2254, 5034, 24123, 11244, 16, 2254, 5034, 437, 352, 11244, 16, 2254, 5034, 433, 495, 624, 10513, 329, 16, 1758, 433, 495, 624, 1345, 16, 2254, 5034, 5184, 11244, 16, 1758, 5184, 1345, 16, 533, 3189, 16, 1426, 63, 26, 65, 2943, 16, 2254, 5034, 14708, 548, 16, 1758, 8808, 7152, 653, 16, 1758, 8808, 3140, 1887, 1769, 203, 565, 871, 348, 500, 2467, 14592, 12, 2867, 8808, 7152, 653, 16, 1758, 8808, 3140, 1887, 16, 2254, 5034, 14708, 548, 16, 2254, 5034, 14708, 1016, 16, 2254, 5034, 5023, 5027, 1769, 203, 565, 871, 17320, 19338, 12, 11890, 5034, 14708, 548, 16, 2254, 5034, 8808, 14708, 1016, 16, 1758, 8808, 7152, 653, 16, 1758, 8808, 3140, 1887, 16, 2254, 28, 2254, 19338, 1769, 203, 565, 871, 4389, 14592, 12, 11890, 5034, 8808, 14708, 1016, 16, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "./libraries/DecimalsConverter.sol"; import "./interfaces/IContractsRegistry.sol"; import "./interfaces/IPolicyBookFacade.sol"; import "./interfaces/IPolicyBook.sol"; import "./interfaces/IPolicyBookRegistry.sol"; import "./interfaces/IShieldMining.sol"; import "./interfaces/IUserLeveragePool.sol"; import "./interfaces/ILeveragePortfolioView.sol"; import "./interfaces/ILeveragePortfolio.sol"; import "./abstract/AbstractDependant.sol"; import "./Globals.sol"; contract ShieldMining is IShieldMining, OwnableUpgradeable, ReentrancyGuard, AbstractDependant { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using Counters for Counters.Counter; using Math for uint256; address public policyBookFabric; IPolicyBookRegistry public policyBookRegistry; mapping(address => ShieldMiningInfo) public shieldMiningInfo; mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid; mapping(address => mapping(address => uint256)) internal _rewards; /// @dev block number to reward per block (to substrate) //deprecated mapping(address => mapping(uint256 => uint256)) public endOfRewards; // new state post v2 Counters.Counter public lastDepositId; mapping(address => EnumerableSet.UintSet) private _usersDepositsId; mapping(uint256 => ShieldMiningDeposit) public usersDeposits; ILeveragePortfolioView public leveragePortfolioView; mapping(address => EnumerableSet.UintSet) internal lastBlockWithRewardList; mapping(address => uint256) public userleveragepoolsParticipatedAmounts; address public bmiCoverStakingAddress; mapping(address => uint256) public userleveragepoolsTotalSupply; event ShieldMiningAssociated(address indexed policyBook, address indexed shieldToken); event ShieldMiningFilled( address indexed policyBook, address indexed shieldToken, address indexed depositor, uint256 amount, uint256 lastBlockWithReward ); event ShieldMiningClaimed(address indexed user, address indexed policyBook, uint256 reward); event ShieldMiningRecovered(address indexed policyBook, uint256 amount); modifier shieldMiningEnabled(address _policyBook) { require( address(shieldMiningInfo[_policyBook].rewardsToken) != address(0), "SM: no shield mining associated" ); _; } modifier updateReward( address _policyBook, address _userLeveragePool, address account ) { _updateReward(_policyBook, _userLeveragePool, account); _; } modifier onlyBMICoverStaking() { require( bmiCoverStakingAddress == _msgSender(), "SM: Caller is not BMICoverStaking contract" ); _; } function __ShieldMining_init() external initializer { __Ownable_init(); } function setDependencies(IContractsRegistry _contractsRegistry) external override onlyInjectorOrZero { policyBookRegistry = IPolicyBookRegistry( _contractsRegistry.getPolicyBookRegistryContract() ); policyBookFabric = _contractsRegistry.getPolicyBookFabricContract(); leveragePortfolioView = ILeveragePortfolioView( _contractsRegistry.getLeveragePortfolioViewContract() ); bmiCoverStakingAddress = _contractsRegistry.getBMICoverStakingContract(); } function blocksWithRewardsPassed(address _policyBook) public view override returns (uint256) { uint256 from = shieldMiningInfo[_policyBook].lastUpdateBlock; uint256 to = Math.min(block.number, shieldMiningInfo[_policyBook].nearestLastBlocksWithReward); return from >= to ? 0 : to.sub(from); } function rewardPerToken(address _policyBook) public view override returns (uint256) { uint256 totalPoolStaked = shieldMiningInfo[_policyBook].totalSupply; if (totalPoolStaked == 0) { return shieldMiningInfo[_policyBook].rewardPerTokenStored; } uint256 accumulatedReward = blocksWithRewardsPassed(_policyBook) .mul(getCurrentRewardPerBlock(_policyBook)) .mul(DECIMALS18) .div(totalPoolStaked); return shieldMiningInfo[_policyBook].rewardPerTokenStored.add(accumulatedReward); } function earned( address _policyBook, address _userLeveragePool, address _account ) public view override returns (uint256) { address _userPool = _userLeveragePool != address(0) ? _userLeveragePool : _policyBook; uint256 rewardsDifference = rewardPerToken(_policyBook).sub(userRewardPerTokenPaid[_account][_userPool]); uint256 userLiquidity; if (_userLeveragePool == address(0)) { userLiquidity = IPolicyBookFacade(IPolicyBook(_policyBook).policyBookFacade()) .userLiquidity(_account); } else { userLiquidity = IUserLeveragePool(_userLeveragePool).userLiquidity(_account); uint256 totalSupply = userleveragepoolsTotalSupply[_userLeveragePool]; if (totalSupply > 0) { userLiquidity = userLiquidity .mul(userleveragepoolsParticipatedAmounts[_userLeveragePool]) .div(totalSupply); } } uint256 newlyAccumulated = userLiquidity.mul(rewardsDifference).div(DECIMALS18); return _rewards[_account][_userPool].add(newlyAccumulated); } function updateTotalSupply( address _policyBook, address _userLeveragePool, address _liquidityProvider ) external override updateReward(_policyBook, _userLeveragePool, _liquidityProvider) { require( policyBookRegistry.isPolicyBookFacade(_msgSender()) || policyBookRegistry.isPolicyBook(_policyBook), "SM: No access" ); uint256 _participatedLeverageAmounts; IPolicyBook _coveragePool = IPolicyBook(_policyBook); IPolicyBookFacade _policyFacade = IPolicyBookFacade(_coveragePool.policyBookFacade()); uint256 _userLeveragePoolsCount = _policyFacade.countUserLeveragePools(); // call from user leverage pool if (_userLeveragePool != address(0)) { _participatedLeverageAmounts = clacParticipatedLeverageAmount( _userLeveragePool, _coveragePool ); userleveragepoolsParticipatedAmounts[_userLeveragePool] = _participatedLeverageAmounts; userleveragepoolsTotalSupply[_userLeveragePool] = IERC20(_userLeveragePool) .totalSupply(); } // call from coverage pool else if (_userLeveragePoolsCount > 0) { address[] memory _userLeverageArr = _policyFacade.listUserLeveragePools(0, _userLeveragePoolsCount); uint256 _participatedLeverageAmount; for (uint256 i = 0; i < _userLeverageArr.length; i++) { _participatedLeverageAmount = clacParticipatedLeverageAmount( _userLeverageArr[i], _coveragePool ); userleveragepoolsParticipatedAmounts[ _userLeveragePool ] = _participatedLeverageAmount; _participatedLeverageAmounts += _participatedLeverageAmount; } } shieldMiningInfo[_policyBook].totalSupply = _participatedLeverageAmounts.add( IERC20(_policyBook).totalSupply() ); } function clacParticipatedLeverageAmount(address _userLeveragePool, IPolicyBook _coveragePool) internal view returns (uint256) { IPolicyBookFacade _policyFacade = IPolicyBookFacade(_coveragePool.policyBookFacade()); uint256 _poolUtilizationRation; uint256 _coverageLiq = _coveragePool.totalLiquidity(); if (_coverageLiq > 0) { _poolUtilizationRation = _coveragePool.totalCoverTokens().mul(PERCENTAGE_100).div( _coverageLiq ); } return _policyFacade .LUuserLeveragePool(_userLeveragePool) .mul(leveragePortfolioView.calcM(_poolUtilizationRation, _userLeveragePool)) .div(PERCENTAGE_100); } function associateShieldMining(address _policyBook, address _shieldMiningToken) external override { require(_msgSender() == policyBookFabric || _msgSender() == owner(), "SM: no access"); require(policyBookRegistry.isPolicyBook(_policyBook), "SM: Not a PolicyBook"); // should revert with "Address: not a contract" if it's an account _shieldMiningToken.functionCall( abi.encodeWithSignature("totalSupply()", ""), "SM: is not an ERC20" ); delete shieldMiningInfo[_policyBook]; shieldMiningInfo[_policyBook].totalSupply = IERC20(_policyBook).totalSupply(); shieldMiningInfo[_policyBook].rewardsToken = IERC20(_shieldMiningToken); shieldMiningInfo[_policyBook].decimals = ERC20(_shieldMiningToken).decimals(); emit ShieldMiningAssociated(_policyBook, _shieldMiningToken); } ///@dev amount should be in decimal18 function fillShieldMining( address _policyBook, uint256 _amount, uint256 _duration ) external override shieldMiningEnabled(_policyBook) { require(_duration >= 22 && _duration <= 366, "SM: out of minimum/maximum duration"); uint256 _tokenDecimals = shieldMiningInfo[_policyBook].decimals; uint256 tokenLiquidity = DecimalsConverter.convertFrom18(_amount, _tokenDecimals); require(tokenLiquidity > 0, "SM: amount is zero"); uint256 _blocksAmount = _duration.mul(BLOCKS_PER_DAY).sub(1); uint256 _rewardPerBlock = _amount.div(_blocksAmount); shieldMiningInfo[_policyBook].rewardsToken.safeTransferFrom( _msgSender(), address(this), tokenLiquidity ); shieldMiningInfo[_policyBook].rewardTokensLocked += _amount; uint256 _lastBlockWithReward = _setRewards(_policyBook, _rewardPerBlock, block.number, _blocksAmount); lastDepositId.increment(); _usersDepositsId[_msgSender()].add(lastDepositId.current()); usersDeposits[lastDepositId.current()] = ShieldMiningDeposit( _policyBook, _amount, _duration, _rewardPerBlock, block.number, _lastBlockWithReward ); emit ShieldMiningFilled( _policyBook, address(shieldMiningInfo[_policyBook].rewardsToken), _msgSender(), _amount, shieldMiningInfo[_policyBook].lastBlockWithReward ); } function getRewardFor( address _user, address _policyBook, address _userLeveragePool ) public override nonReentrant updateReward(_policyBook, _userLeveragePool, _user) onlyBMICoverStaking { _getReward(_user, _policyBook, _userLeveragePool); } function getRewardFor(address _user, address _userLeveragePool) public override nonReentrant onlyBMICoverStaking { _getRewardFromLeverage(_user, _userLeveragePool, true); } function getReward(address _policyBook, address _userLeveragePool) public override nonReentrant updateReward(_policyBook, _userLeveragePool, _msgSender()) { _getReward(_msgSender(), _policyBook, _userLeveragePool); } function getReward(address _userLeveragePool) public override nonReentrant { _getRewardFromLeverage(_msgSender(), _userLeveragePool, false); } function _getRewardFromLeverage( address _user, address _userLeveragePool, bool isRewardFor ) internal { ILeveragePortfolio userLeveragePool = ILeveragePortfolio(_userLeveragePool); address[] memory _coveragePools = userLeveragePool.listleveragedCoveragePools( 0, userLeveragePool.countleveragedCoveragePools() ); for (uint256 i = 0; i < _coveragePools.length; i++) { if (getShieldTokenAddress(_coveragePools[i]) != address(0)) { if (isRewardFor) { getRewardFor(_user, _coveragePools[i], _userLeveragePool); } else { getReward(_coveragePools[i], _userLeveragePool); } } } } function _getReward( address _user, address _policyBook, address _userLeveragePool ) internal { address _userPool = _userLeveragePool != address(0) ? _userLeveragePool : _policyBook; uint256 reward = _rewards[_user][_userPool]; if (reward > 0) { delete _rewards[_user][_userPool]; uint256 _tokenDecimals = shieldMiningInfo[_policyBook].decimals; // transfer profit to the user shieldMiningInfo[_policyBook].rewardsToken.safeTransfer( _user, DecimalsConverter.convertFrom18(reward, _tokenDecimals) ); shieldMiningInfo[_policyBook].rewardTokensLocked -= reward; emit ShieldMiningClaimed(_user, _policyBook, reward); } } function recoverNonLockedRewardTokens(address _policyBook) public onlyOwner { uint256 _tokenDecimals = shieldMiningInfo[_policyBook].decimals; uint256 _futureRewardTokens = _getFutureRewardTokens(_policyBook); uint256 tokenBalance = DecimalsConverter.convertTo18( shieldMiningInfo[_policyBook].rewardsToken.balanceOf(address(this)), _tokenDecimals ); if (tokenBalance > _futureRewardTokens) { uint256 nonLockedTokens = tokenBalance.sub(_futureRewardTokens); shieldMiningInfo[_policyBook].rewardsToken.safeTransfer( owner(), DecimalsConverter.convertFrom18(nonLockedTokens, _tokenDecimals) ); emit ShieldMiningRecovered(_policyBook, nonLockedTokens); } } function getShieldTokenAddress(address _policyBook) public view override returns (address) { return address(shieldMiningInfo[_policyBook].rewardsToken); } function getShieldMiningInfo(address _policyBook) external view override returns ( address _rewardsToken, uint256 _decimals, uint256 _firstBlockWithReward, uint256 _lastBlockWithReward, uint256 _lastUpdateBlock, uint256 _nearestLastBlocksWithReward, uint256 _rewardTokensLocked, uint256 _rewardPerTokenStored, uint256 _rewardPerBlock, uint256 _tokenPerDay, uint256 _totalSupply ) { _rewardsToken = address(shieldMiningInfo[_policyBook].rewardsToken); _decimals = shieldMiningInfo[_policyBook].decimals; _firstBlockWithReward = shieldMiningInfo[_policyBook].firstBlockWithReward; _lastBlockWithReward = shieldMiningInfo[_policyBook].lastBlockWithReward; _lastUpdateBlock = shieldMiningInfo[_policyBook].lastUpdateBlock; _nearestLastBlocksWithReward = shieldMiningInfo[_policyBook].nearestLastBlocksWithReward; _rewardPerTokenStored = shieldMiningInfo[_policyBook].rewardPerTokenStored; _rewardPerBlock = getCurrentRewardPerBlock(_policyBook); _tokenPerDay = _rewardPerBlock.mul(BLOCKS_PER_DAY); _totalSupply = shieldMiningInfo[_policyBook].totalSupply; _rewardTokensLocked = shieldMiningInfo[_policyBook].rewardTokensLocked; } function getDepositList( address _account, uint256 _offset, uint256 _limit ) external view override returns (ShieldMiningDeposit[] memory _depositsList) { uint256 nbOfDeposit = _usersDepositsId[_account].length(); uint256 to = (_offset.add(_limit)).min(nbOfDeposit).max(_offset); uint256 size = to.sub(_offset); _depositsList = new ShieldMiningDeposit[](size); for (uint256 i = _offset; i < to; i++) { ShieldMiningDeposit memory smd = usersDeposits[_usersDepositsId[_account].at(i)]; _depositsList[i].policyBook = smd.policyBook; _depositsList[i].amount = smd.amount; _depositsList[i].duration = smd.duration; _depositsList[i].depositRewardPerBlock = smd.depositRewardPerBlock; _depositsList[i].startBlock = smd.startBlock; _depositsList[i].endBlock = smd.endBlock; } } /// @notice get count of user deposits function countUsersDeposits(address _account) external view override returns (uint256) { return _usersDepositsId[_account].length(); } function _setRewards( address _policyBook, uint256 _rewardPerBlock, uint256 _startingBlock, uint256 _blocksAmount ) internal updateReward(_policyBook, address(0), address(0)) returns (uint256 _lastBlockWithReward) { shieldMiningInfo[_policyBook].firstBlockWithReward = _startingBlock; _lastBlockWithReward = _startingBlock.add(_blocksAmount); if (shieldMiningInfo[_policyBook].lastBlockWithReward < _lastBlockWithReward) { shieldMiningInfo[_policyBook].lastBlockWithReward = _lastBlockWithReward; } shieldMiningInfo[_policyBook].rewardPerBlock[_lastBlockWithReward] += _rewardPerBlock; lastBlockWithRewardList[_policyBook].add(_lastBlockWithReward); } function _updateReward( address _policyBook, address _userLeveragePool, address _account ) internal { _updateNearestLastBlocksWithReward(_policyBook); uint256 currentRewardPerToken = rewardPerToken(_policyBook); shieldMiningInfo[_policyBook].rewardPerTokenStored = currentRewardPerToken; uint256 _nearestLastBlocksWithReward = shieldMiningInfo[_policyBook].nearestLastBlocksWithReward; uint256 _lastBlockWithReward = shieldMiningInfo[_policyBook].lastBlockWithReward; if ( _nearestLastBlocksWithReward != 0 && block.number > _nearestLastBlocksWithReward && _lastBlockWithReward != _nearestLastBlocksWithReward ) { shieldMiningInfo[_policyBook].lastUpdateBlock = _nearestLastBlocksWithReward; lastBlockWithRewardList[_policyBook].remove(_nearestLastBlocksWithReward); _updateReward(_policyBook, _userLeveragePool, _account); } else { shieldMiningInfo[_policyBook].lastUpdateBlock = block.number; } if (_account != address(0)) { address _userPool = _userLeveragePool != address(0) ? _userLeveragePool : _policyBook; _rewards[_account][_userPool] = earned(_policyBook, _userLeveragePool, _account); userRewardPerTokenPaid[_account][_userPool] = currentRewardPerToken; } } function getCurrentRewardPerBlock(address _policyBook) public view returns (uint256 _rewardPerBlock) { uint256 _lastUpdateBlock = shieldMiningInfo[_policyBook].lastUpdateBlock; for (uint256 i = 0; i < lastBlockWithRewardList[_policyBook].length(); i++) { uint256 _lastBlockWithReward = lastBlockWithRewardList[_policyBook].at(i); uint256 _firstBlockWithReward = lastBlockWithRewardList[_policyBook].at(i); if (_lastBlockWithReward > _lastUpdateBlock && _firstBlockWithReward != block.number) { _rewardPerBlock += shieldMiningInfo[_policyBook].rewardPerBlock[ _lastBlockWithReward ]; } } } function _updateNearestLastBlocksWithReward(address _policyBook) internal { uint256 _lastUpdateBlock = shieldMiningInfo[_policyBook].lastUpdateBlock; uint256 _lastBlockWithReward = shieldMiningInfo[_policyBook].lastBlockWithReward; uint256 _nearestLastBlocksWithReward = _lastBlockWithReward; uint256 _lastBlock; for (uint256 i = 0; i < lastBlockWithRewardList[_policyBook].length(); i++) { _lastBlock = lastBlockWithRewardList[_policyBook].at(i); if (_lastBlock <= _nearestLastBlocksWithReward && _lastUpdateBlock < _lastBlock) { _nearestLastBlocksWithReward = _lastBlock; } } shieldMiningInfo[_policyBook].nearestLastBlocksWithReward = _nearestLastBlocksWithReward; } function _getFutureRewardTokens(address _policyBook) internal view returns (uint256 _futureRewardTokens) { uint256 _lastUpdateBlock = shieldMiningInfo[_policyBook].lastUpdateBlock; for (uint256 i = 0; i < lastBlockWithRewardList[_policyBook].length(); i++) { uint256 _lastBlockWithReward = lastBlockWithRewardList[_policyBook].at(i); uint256 blocksLeft = _calculateBlocksLeft(_lastUpdateBlock, _lastBlockWithReward); _futureRewardTokens += blocksLeft.mul( shieldMiningInfo[_policyBook].rewardPerBlock[_lastBlockWithReward] ); } } function _calculateBlocksLeft(uint256 _from, uint256 _to) internal view returns (uint256) { if (block.number >= _to) return 0; if (block.number < _from) return _to.sub(_from).add(1); return _to.sub(block.number); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.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)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <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 {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../GSN/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @notice the intention of this library is to be able to easily convert /// one amount of tokens with N decimal places /// to another amount with M decimal places library DecimalsConverter { using SafeMath for uint256; function convert( uint256 amount, uint256 baseDecimals, uint256 destinationDecimals ) internal pure returns (uint256) { if (baseDecimals > destinationDecimals) { amount = amount.div(10**(baseDecimals - destinationDecimals)); } else if (baseDecimals < destinationDecimals) { amount = amount.mul(10**(destinationDecimals - baseDecimals)); } return amount; } function convertTo18(uint256 amount, uint256 baseDecimals) internal pure returns (uint256) { return convert(amount, baseDecimals, 18); } function convertFrom18(uint256 amount, uint256 destinationDecimals) internal pure returns (uint256) { return convert(amount, 18, destinationDecimals); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; import "./IClaimingRegistry.sol"; import "./IPolicyBookFacade.sol"; interface IUserLeveragePool { enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED} struct WithdrawalInfo { uint256 withdrawalAmount; uint256 readyToWithdrawDate; bool withdrawalAllowed; } struct BMIMultiplierFactors { uint256 poolMultiplier; uint256 leverageProvided; uint256 multiplier; } /// @notice Returns type of contract this PolicyBook covers, access: ANY /// @return _type is type of contract function contractType() external view returns (IPolicyBookFabric.ContractType _type); function userLiquidity(address account) external view returns (uint256); function EPOCH_DURATION() external view returns (uint256); function READY_TO_WITHDRAW_PERIOD() external view returns (uint256); function epochStartTime() external view returns (uint256); function withdrawalsInfo(address _userAddr) external view returns ( uint256 _withdrawalAmount, uint256 _readyToWithdrawDate, bool _withdrawalAllowed ); function __UserLeveragePool_init( IPolicyBookFabric.ContractType _contractType, string calldata _description, string calldata _projectSymbol ) external; function getEpoch(uint256 time) external view returns (uint256); /// @notice get STBL equivalent function convertBMIXToSTBL(uint256 _amount) external view returns (uint256); /// @notice get BMIX equivalent function convertSTBLToBMIX(uint256 _amount) external view returns (uint256); /// @notice forces an update of RewardsGenerator multiplier function forceUpdateBMICoverStakingRewardMultiplier() external; /// @notice function to get precise current cover and liquidity function getNewCoverAndLiquidity() external view returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity); function updateEpochsInfo() external; function secondsToEndCurrentEpoch() external view returns (uint256); /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _liqudityAmount is amount of stable coin tokens to secure function addLiquidity(uint256 _liqudityAmount) external; // /// @notice Let eligible contracts add liqiudity for another user by supplying stable coin // /// @param _liquidityHolderAddr is address of address to assign cover // /// @param _liqudityAmount is amount of stable coin tokens to secure // function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external; function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external; function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256); function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus); function requestWithdrawal(uint256 _tokensToWithdraw) external; // function requestWithdrawalWithPermit( // uint256 _tokensToWithdraw, // uint8 _v, // bytes32 _r, // bytes32 _s // ) external; function unlockTokens() external; /// @notice Let user to withdraw deposited liqiudity, access: ANY function withdrawLiquidity() external; ///@notice for doing defi hard rebalancing, access: CapitalPool function updateLiquidity(uint256 _newLiquidity) external; function getAPY() external view returns (uint256); function whitelisted() external view returns (bool); function whitelist(bool _whitelisted) external; /// @notice set max total liquidity for the pool /// @param _maxCapacities uint256 the max total liquidity function setMaxCapacities(uint256 _maxCapacities) external; /// @notice Getting number stats, access: ANY /// @return _maxCapacities is a max liquidity of the pool /// @return _totalSTBLLiquidity is PolicyBook's liquidity /// @return _totalLeveragedLiquidity is becuase to follow the same function in policy book /// @return _stakedSTBL is how much stable coin are staked on this PolicyBook /// @return _annualProfitYields is its APY /// @return _annualInsuranceCost is becuase to follow the same function in policy book /// @return _bmiXRatio is multiplied by 10**18. To get STBL representation function numberStats() external view returns ( uint256 _maxCapacities, uint256 _totalSTBLLiquidity, uint256 _totalLeveragedLiquidity, uint256 _stakedSTBL, uint256 _annualProfitYields, uint256 _annualInsuranceCost, uint256 _bmiXRatio ); /// @notice Getting info, access: ANY /// @return _symbol is the symbol of PolicyBook (bmiXCover) /// @return _insuredContract is an addres of insured contract /// @return _contractType is becuase to follow the same function in policy book /// @return _whitelisted is a state of whitelisting function info() external view returns ( string memory _symbol, address _insuredContract, IPolicyBookFabric.ContractType _contractType, bool _whitelisted ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IShieldMining { struct ShieldMiningInfo { IERC20 rewardsToken; uint8 decimals; uint256 firstBlockWithReward; uint256 lastBlockWithReward; uint256 lastUpdateBlock; uint256 rewardTokensLocked; uint256 rewardPerTokenStored; uint256 totalSupply; uint256[] endsOfDistribution; // new state post v2 uint256 nearestLastBlocksWithReward; // lastBlockWithReward => rewardPerBlock mapping(uint256 => uint256) rewardPerBlock; } struct ShieldMiningDeposit { address policyBook; uint256 amount; uint256 duration; uint256 depositRewardPerBlock; uint256 startBlock; uint256 endBlock; } /// TODO document SM functions function blocksWithRewardsPassed(address _policyBook) external view returns (uint256); function rewardPerToken(address _policyBook) external view returns (uint256); function earned( address _policyBook, address _userLeveragePool, address _account ) external view returns (uint256); function updateTotalSupply( address _policyBook, address _userLeveragePool, address liquidityProvider ) external; function associateShieldMining(address _policyBook, address _shieldMiningToken) external; function fillShieldMining( address _policyBook, uint256 _amount, uint256 _duration ) external; function getRewardFor( address _userAddress, address _policyBook, address _userLeveragePool ) external; function getRewardFor(address _userAddress, address _userLeveragePoolAddress) external; function getReward(address _policyBook, address _userLeveragePool) external; function getReward(address _userLeveragePoolAddress) external; function getShieldTokenAddress(address _policyBook) external view returns (address); function getShieldMiningInfo(address _policyBook) external view returns ( address _rewardsToken, uint256 _decimals, uint256 _firstBlockWithReward, uint256 _lastBlockWithReward, uint256 _lastUpdateBlock, uint256 _nearestLastBlocksWithReward, uint256 _rewardTokensLocked, uint256 _rewardPerTokenStored, uint256 _rewardPerBlock, uint256 _tokenPerDay, uint256 _totalSupply ); function getDepositList( address _account, uint256 _offset, uint256 _limit ) external view returns (ShieldMiningDeposit[] memory _depositsList); function countUsersDeposits(address _account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; interface IPolicyBookRegistry { struct PolicyBookStats { string symbol; address insuredContract; IPolicyBookFabric.ContractType contractType; uint256 maxCapacity; uint256 totalSTBLLiquidity; uint256 totalLeveragedLiquidity; uint256 stakedSTBL; uint256 APY; uint256 annualInsuranceCost; uint256 bmiXRatio; bool whitelisted; } function policyBooksByInsuredAddress(address insuredContract) external view returns (address); function policyBookFacades(address facadeAddress) external view returns (address); /// @notice Adds PolicyBook to registry, access: PolicyFabric function add( address insuredContract, IPolicyBookFabric.ContractType contractType, address policyBook, address facadeAddress ) external; function whitelist(address policyBookAddress, bool whitelisted) external; /// @notice returns required allowances for the policybooks function getPoliciesPrices( address[] calldata policyBooks, uint256[] calldata epochsNumbers, uint256[] calldata coversTokens ) external view returns (uint256[] memory _durations, uint256[] memory _allowances); /// @notice Buys a batch of policies function buyPolicyBatch( address[] calldata policyBooks, uint256[] calldata epochsNumbers, uint256[] calldata coversTokens ) external; /// @notice Checks if provided address is a PolicyBook function isPolicyBook(address policyBook) external view returns (bool); /// @notice Checks if provided address is a policyBookFacade function isPolicyBookFacade(address _facadeAddress) external view returns (bool); /// @notice Checks if provided address is a user leverage pool function isUserLeveragePool(address policyBookAddress) external view returns (bool); /// @notice Returns number of registered PolicyBooks with certain contract type function countByType(IPolicyBookFabric.ContractType contractType) external view returns (uint256); /// @notice Returns number of registered PolicyBooks, access: ANY function count() external view returns (uint256); function countByTypeWhitelisted(IPolicyBookFabric.ContractType contractType) external view returns (uint256); function countWhitelisted() external view returns (uint256); /// @notice Listing registered PolicyBooks with certain contract type, access: ANY /// @return _policyBooksArr is array of registered PolicyBook addresses with certain contract type function listByType( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr); /// @notice Listing registered PolicyBooks, access: ANY /// @return _policyBooksArr is array of registered PolicyBook addresses function list(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr); function listByTypeWhitelisted( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr); function listWhitelisted(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr); /// @notice Listing registered PolicyBooks with stats and certain contract type, access: ANY function listWithStatsByType( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); /// @notice Listing registered PolicyBooks with stats, access: ANY function listWithStats(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); function listWithStatsByTypeWhitelisted( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); function listWithStatsWhitelisted(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); /// @notice Getting stats from policy books, access: ANY /// @param policyBooks is list of PolicyBooks addresses function stats(address[] calldata policyBooks) external view returns (PolicyBookStats[] memory _stats); /// @notice Return existing Policy Book contract, access: ANY /// @param insuredContract is contract address to lookup for created IPolicyBook function policyBookFor(address insuredContract) external view returns (address); /// @notice Getting stats from policy books, access: ANY /// @param insuredContracts is list of insuredContracts in registry function statsByInsuredContracts(address[] calldata insuredContracts) external view returns (PolicyBookStats[] memory _stats); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "./IPolicyBook.sol"; import "./ILeveragePortfolio.sol"; interface IPolicyBookFacade { /// @notice Let user to buy policy by supplying stable coin, access: ANY /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage function buyPolicy(uint256 _epochsNumber, uint256 _coverTokens) external; /// @param _holder who owns coverage /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage function buyPolicyFor( address _holder, uint256 _epochsNumber, uint256 _coverTokens ) external; function policyBook() external view returns (IPolicyBook); function userLiquidity(address account) external view returns (uint256); /// @notice virtual funds deployed by reinsurance pool function VUreinsurnacePool() external view returns (uint256); /// @notice leverage funds deployed by reinsurance pool function LUreinsurnacePool() external view returns (uint256); /// @notice leverage funds deployed by user leverage pool function LUuserLeveragePool(address userLeveragePool) external view returns (uint256); /// @notice total leverage funds deployed to the pool sum of (VUreinsurnacePool,LUreinsurnacePool,LUuserLeveragePool) function totalLeveragedLiquidity() external view returns (uint256); function userleveragedMPL() external view returns (uint256); function reinsurancePoolMPL() external view returns (uint256); function rebalancingThreshold() external view returns (uint256); function safePricingModel() external view returns (bool); /// @notice policyBookFacade initializer /// @param pbProxy polciybook address upgreadable cotnract. function __PolicyBookFacade_init( address pbProxy, address liquidityProvider, uint256 initialDeposit ) external; /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage /// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission) function buyPolicyFromDistributor( uint256 _epochsNumber, uint256 _coverTokens, address _distributor ) external; /// @param _buyer who is buying the coverage /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage /// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission) function buyPolicyFromDistributorFor( address _buyer, uint256 _epochsNumber, uint256 _coverTokens, address _distributor ) external; /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _liquidityAmount is amount of stable coin tokens to secure function addLiquidity(uint256 _liquidityAmount) external; /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _user the one taht add liquidity /// @param _liquidityAmount is amount of stable coin tokens to secure function addLiquidityFromDistributorFor(address _user, uint256 _liquidityAmount) external; /// @notice Let user to add liquidity by supplying stable coin and stake it, /// @dev access: ANY function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external; /// @notice Let user to withdraw deposited liqiudity, access: ANY function withdrawLiquidity() external; /// @notice fetches all the pools data /// @return uint256 VUreinsurnacePool /// @return uint256 LUreinsurnacePool /// @return uint256 LUleveragePool /// @return uint256 user leverage pool address function getPoolsData() external view returns ( uint256, uint256, uint256, address ); /// @notice deploy leverage funds (RP lStable, ULP lStable) /// @param deployedAmount uint256 the deployed amount to be added or substracted from the total liquidity /// @param leveragePool whether user leverage or reinsurance leverage function deployLeverageFundsAfterRebalance( uint256 deployedAmount, ILeveragePortfolio.LeveragePortfolio leveragePool ) external; /// @notice deploy virtual funds (RP vStable) /// @param deployedAmount uint256 the deployed amount to be added to the liquidity function deployVirtualFundsAfterRebalance(uint256 deployedAmount) external; /// @notice set the MPL for the user leverage and the reinsurance leverage /// @param _userLeverageMPL uint256 value of the user leverage MPL /// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage MPL function setMPLs(uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL) external; /// @notice sets the rebalancing threshold value /// @param _newRebalancingThreshold uint256 rebalancing threshhold value function setRebalancingThreshold(uint256 _newRebalancingThreshold) external; /// @notice sets the rebalancing threshold value /// @param _safePricingModel bool is pricing model safe (true) or not (false) function setSafePricingModel(bool _safePricingModel) external; /// @notice returns how many BMI tokens needs to approve in order to submit a claim function getClaimApprovalAmount(address user) external view returns (uint256); /// @notice upserts a withdraw request /// @dev prevents adding a request if an already pending or ready request is open. /// @param _tokensToWithdraw uint256 amount of tokens to withdraw function requestWithdrawal(uint256 _tokensToWithdraw) external; function listUserLeveragePools(uint256 offset, uint256 limit) external view returns (address[] memory _userLeveragePools); function countUserLeveragePools() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface IPolicyBookFabric { enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE, VARIOUS} /// @notice Create new Policy Book contract, access: ANY /// @param _contract is Contract to create policy book for /// @param _contractType is Contract to create policy book for /// @param _description is bmiXCover token desription for this policy book /// @param _projectSymbol replaces x in bmiXCover token symbol /// @param _initialDeposit is an amount user deposits on creation (addLiquidity()) /// @return _policyBook is address of created contract function create( address _contract, ContractType _contractType, string calldata _description, string calldata _projectSymbol, uint256 _initialDeposit, address _shieldMiningToken ) external returns (address); function createLeveragePools( ContractType _contractType, string calldata _description, string calldata _projectSymbol ) external returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; import "./IClaimingRegistry.sol"; import "./IPolicyBookFacade.sol"; interface IPolicyBook { enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED} struct PolicyHolder { uint256 coverTokens; uint256 startEpochNumber; uint256 endEpochNumber; uint256 paid; uint256 reinsurancePrice; } struct WithdrawalInfo { uint256 withdrawalAmount; uint256 readyToWithdrawDate; bool withdrawalAllowed; } struct BuyPolicyParameters { address buyer; address holder; uint256 epochsNumber; uint256 coverTokens; uint256 distributorFee; address distributor; } function policyHolders(address _holder) external view returns ( uint256, uint256, uint256, uint256, uint256 ); function policyBookFacade() external view returns (IPolicyBookFacade); function setPolicyBookFacade(address _policyBookFacade) external; function EPOCH_DURATION() external view returns (uint256); function stblDecimals() external view returns (uint256); function READY_TO_WITHDRAW_PERIOD() external view returns (uint256); function whitelisted() external view returns (bool); function epochStartTime() external view returns (uint256); // @TODO: should we let DAO to change contract address? /// @notice Returns address of contract this PolicyBook covers, access: ANY /// @return _contract is address of covered contract function insuranceContractAddress() external view returns (address _contract); /// @notice Returns type of contract this PolicyBook covers, access: ANY /// @return _type is type of contract function contractType() external view returns (IPolicyBookFabric.ContractType _type); function totalLiquidity() external view returns (uint256); function totalCoverTokens() external view returns (uint256); // /// @notice return MPL for user leverage pool // function userleveragedMPL() external view returns (uint256); // /// @notice return MPL for reinsurance pool // function reinsurancePoolMPL() external view returns (uint256); // function bmiRewardMultiplier() external view returns (uint256); function withdrawalsInfo(address _userAddr) external view returns ( uint256 _withdrawalAmount, uint256 _readyToWithdrawDate, bool _withdrawalAllowed ); function __PolicyBook_init( address _insuranceContract, IPolicyBookFabric.ContractType _contractType, string calldata _description, string calldata _projectSymbol ) external; function whitelist(bool _whitelisted) external; function getEpoch(uint256 time) external view returns (uint256); /// @notice get STBL equivalent function convertBMIXToSTBL(uint256 _amount) external view returns (uint256); /// @notice get BMIX equivalent function convertSTBLToBMIX(uint256 _amount) external view returns (uint256); /// @notice submits new claim of the policy book function submitClaimAndInitializeVoting(string calldata evidenceURI) external; /// @notice submits new appeal claim of the policy book function submitAppealAndInitializeVoting(string calldata evidenceURI) external; /// @notice updates info on claim acceptance function commitClaim( address claimer, uint256 claimAmount, uint256 claimEndTime, IClaimingRegistry.ClaimStatus status ) external; /// @notice forces an update of RewardsGenerator multiplier function forceUpdateBMICoverStakingRewardMultiplier() external; /// @notice function to get precise current cover and liquidity function getNewCoverAndLiquidity() external view returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity); /// @notice view function to get precise policy price /// @param _epochsNumber is number of epochs to cover /// @param _coverTokens is number of tokens to cover /// @param _buyer address of the user who buy the policy /// @return totalSeconds is number of seconds to cover /// @return totalPrice is the policy price which will pay by the buyer function getPolicyPrice( uint256 _epochsNumber, uint256 _coverTokens, address _buyer ) external view returns ( uint256 totalSeconds, uint256 totalPrice, uint256 pricePercentage ); /// @notice Let user to buy policy by supplying stable coin, access: ANY /// @param _buyer who is transferring funds /// @param _holder who owns coverage /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage /// @param _distributorFee distributor fee (commission). It can't be greater than PROTOCOL_PERCENTAGE /// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission) function buyPolicy( address _buyer, address _holder, uint256 _epochsNumber, uint256 _coverTokens, uint256 _distributorFee, address _distributor ) external returns (uint256, uint256); function updateEpochsInfo() external; function secondsToEndCurrentEpoch() external view returns (uint256); /// @notice Let eligible contracts add liqiudity for another user by supplying stable coin /// @param _liquidityHolderAddr is address of address to assign cover /// @param _liqudityAmount is amount of stable coin tokens to secure function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external; /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _liquidityBuyerAddr address the one that transfer funds /// @param _liquidityHolderAddr address the one that owns liquidity /// @param _liquidityAmount uint256 amount to be added on behalf the sender /// @param _stakeSTBLAmount uint256 the staked amount if add liq and stake function addLiquidity( address _liquidityBuyerAddr, address _liquidityHolderAddr, uint256 _liquidityAmount, uint256 _stakeSTBLAmount ) external returns (uint256); function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256); function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus); function requestWithdrawal(uint256 _tokensToWithdraw, address _user) external; // function requestWithdrawalWithPermit( // uint256 _tokensToWithdraw, // uint8 _v, // bytes32 _r, // bytes32 _s // ) external; function unlockTokens() external; /// @notice Let user to withdraw deposited liqiudity, access: ANY function withdrawLiquidity(address sender) external returns (uint256); ///@notice for doing defi hard rebalancing, access: policyBookFacade function updateLiquidity(uint256 _newLiquidity) external; function getAPY() external view returns (uint256); /// @notice Getting user stats, access: ANY function userStats(address _user) external view returns (PolicyHolder memory); /// @notice Getting number stats, access: ANY /// @return _maxCapacities is a max token amount that a user can buy /// @return _totalSTBLLiquidity is PolicyBook's liquidity /// @return _totalLeveragedLiquidity is PolicyBook's leveraged liquidity /// @return _stakedSTBL is how much stable coin are staked on this PolicyBook /// @return _annualProfitYields is its APY /// @return _annualInsuranceCost is percentage of cover tokens that is required to be paid for 1 year of insurance function numberStats() external view returns ( uint256 _maxCapacities, uint256 _totalSTBLLiquidity, uint256 _totalLeveragedLiquidity, uint256 _stakedSTBL, uint256 _annualProfitYields, uint256 _annualInsuranceCost, uint256 _bmiXRatio ); /// @notice Getting info, access: ANY /// @return _symbol is the symbol of PolicyBook (bmiXCover) /// @return _insuredContract is an addres of insured contract /// @return _contractType is a type of insured contract /// @return _whitelisted is a state of whitelisting function info() external view returns ( string memory _symbol, address _insuredContract, IPolicyBookFabric.ContractType _contractType, bool _whitelisted ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./ILeveragePortfolio.sol"; import "./IUserLeveragePool.sol"; interface ILeveragePortfolioView { function calcM(uint256 poolUR, address leveragePoolAddress) external view returns (uint256); function calcMaxLevFunds(ILeveragePortfolio.LevFundsFactors memory factors) external view returns (uint256); function calcBMIMultiplier(IUserLeveragePool.BMIMultiplierFactors memory factors) external view returns (uint256); function getPolicyBookFacade(address _policybookAddress) external view returns (IPolicyBookFacade _coveragePool); function calcNetMPLn( ILeveragePortfolio.LeveragePortfolio leveragePoolType, address _policyBookFacade ) external view returns (uint256 _netMPLn); function calcMaxVirtualFunds(address policyBookAddress) external returns (uint256 _amountToDeploy, uint256 _maxAmount); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface ILeveragePortfolio { enum LeveragePortfolio {USERLEVERAGEPOOL, REINSURANCEPOOL} struct LevFundsFactors { uint256 netMPL; uint256 netMPLn; address policyBookAddr; } function targetUR() external view returns (uint256); function d_ProtocolConstant() external view returns (uint256); function a_ProtocolConstant() external view returns (uint256); function a2_ProtocolConstant() external view returns (uint256); function max_ProtocolConstant() external view returns (uint256); /// @notice deploy lStable from user leverage pool or reinsurance pool using 2 formulas: access by policybook. /// @param leveragePoolType LeveragePortfolio is determine the pool which call the function function deployLeverageStableToCoveragePools(LeveragePortfolio leveragePoolType) external returns (uint256); /// @notice deploy the vStable from RP in v2 and for next versions it will be from RP and LP : access by policybook. function deployVirtualStableToCoveragePools() external returns (uint256); /// @notice set the threshold % for re-evaluation of the lStable provided across all Coverage pools : access by owner /// @param threshold uint256 is the reevaluatation threshold function setRebalancingThreshold(uint256 threshold) external; /// @notice set the protocol constant : access by owner /// @param _targetUR uint256 target utitlization ration /// @param _d_ProtocolConstant uint256 D protocol constant /// @param _a1_ProtocolConstant uint256 A1 protocol constant /// @param _a2_ProtocolConstant uint256 A2 protocol constant /// @param _max_ProtocolConstant uint256 the max % included function setProtocolConstant( uint256 _targetUR, uint256 _d_ProtocolConstant, uint256 _a1_ProtocolConstant, uint256 _a2_ProtocolConstant, uint256 _max_ProtocolConstant ) external; /// @notice calc M factor by formual M = min( abs((1/ (Tur-UR))*d) /a, max) /// @param poolUR uint256 utitilization ratio for a coverage pool /// @return uint256 M facotr //function calcM(uint256 poolUR) external returns (uint256); /// @return uint256 the amount of vStable stored in the pool function totalLiquidity() external view returns (uint256); /// @notice add the portion of 80% of premium to user leverage pool where the leverage provide lstable : access policybook /// add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable) : access policybook /// @param epochsNumber uint256 the number of epochs which the policy holder will pay a premium for /// @param premiumAmount uint256 the premium amount which is a portion of 80% of the premium function addPolicyPremium(uint256 epochsNumber, uint256 premiumAmount) external; /// @notice Used to get a list of coverage pools which get leveraged , use with count() /// @return _coveragePools a list containing policybook addresses function listleveragedCoveragePools(uint256 offset, uint256 limit) external view returns (address[] memory _coveragePools); /// @notice get count of coverage pools which get leveraged function countleveragedCoveragePools() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface IContractsRegistry { function getUniswapRouterContract() external view returns (address); function getUniswapBMIToETHPairContract() external view returns (address); function getUniswapBMIToUSDTPairContract() external view returns (address); function getSushiswapRouterContract() external view returns (address); function getSushiswapBMIToETHPairContract() external view returns (address); function getSushiswapBMIToUSDTPairContract() external view returns (address); function getSushiSwapMasterChefV2Contract() external view returns (address); function getWETHContract() external view returns (address); function getUSDTContract() external view returns (address); function getBMIContract() external view returns (address); function getPriceFeedContract() external view returns (address); function getPolicyBookRegistryContract() external view returns (address); function getPolicyBookFabricContract() external view returns (address); function getBMICoverStakingContract() external view returns (address); function getBMICoverStakingViewContract() external view returns (address); function getLegacyRewardsGeneratorContract() external view returns (address); function getRewardsGeneratorContract() external view returns (address); function getBMIUtilityNFTContract() external view returns (address); function getNFTStakingContract() external view returns (address); function getLiquidityMiningContract() external view returns (address); function getClaimingRegistryContract() external view returns (address); function getPolicyRegistryContract() external view returns (address); function getLiquidityRegistryContract() external view returns (address); function getClaimVotingContract() external view returns (address); function getReinsurancePoolContract() external view returns (address); function getLeveragePortfolioViewContract() external view returns (address); function getCapitalPoolContract() external view returns (address); function getPolicyBookAdminContract() external view returns (address); function getPolicyQuoteContract() external view returns (address); function getLegacyBMIStakingContract() external view returns (address); function getBMIStakingContract() external view returns (address); function getSTKBMIContract() external view returns (address); function getVBMIContract() external view returns (address); function getLegacyLiquidityMiningStakingContract() external view returns (address); function getLiquidityMiningStakingETHContract() external view returns (address); function getLiquidityMiningStakingUSDTContract() external view returns (address); function getReputationSystemContract() external view returns (address); function getAaveProtocolContract() external view returns (address); function getAaveLendPoolAddressProvdierContract() external view returns (address); function getAaveATokenContract() external view returns (address); function getCompoundProtocolContract() external view returns (address); function getCompoundCTokenContract() external view returns (address); function getCompoundComptrollerContract() external view returns (address); function getYearnProtocolContract() external view returns (address); function getYearnVaultContract() external view returns (address); function getYieldGeneratorContract() external view returns (address); function getShieldMiningContract() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; interface IClaimingRegistry { enum ClaimStatus { CAN_CLAIM, UNCLAIMABLE, PENDING, AWAITING_CALCULATION, REJECTED_CAN_APPEAL, REJECTED, ACCEPTED } struct ClaimInfo { address claimer; address policyBookAddress; string evidenceURI; uint256 dateSubmitted; uint256 dateEnded; bool appeal; ClaimStatus status; uint256 claimAmount; } /// @notice returns anonymous voting duration function anonymousVotingDuration(uint256 index) external view returns (uint256); /// @notice returns the whole voting duration function votingDuration(uint256 index) external view returns (uint256); /// @notice returns how many time should pass before anyone could calculate a claim result function anyoneCanCalculateClaimResultAfter(uint256 index) external view returns (uint256); /// @notice returns true if a user can buy new policy of specified PolicyBook function canBuyNewPolicy(address buyer, address policyBookAddress) external view returns (bool); /// @notice submits new PolicyBook claim for the user function submitClaim( address user, address policyBookAddress, string calldata evidenceURI, uint256 cover, bool appeal ) external returns (uint256); /// @notice returns true if the claim with this index exists function claimExists(uint256 index) external view returns (bool); /// @notice returns claim submition time function claimSubmittedTime(uint256 index) external view returns (uint256); /// @notice returns claim end time or zero in case it is pending function claimEndTime(uint256 index) external view returns (uint256); /// @notice returns true if the claim is anonymously votable function isClaimAnonymouslyVotable(uint256 index) external view returns (bool); /// @notice returns true if the claim is exposably votable function isClaimExposablyVotable(uint256 index) external view returns (bool); /// @notice returns true if claim is anonymously votable or exposably votable function isClaimVotable(uint256 index) external view returns (bool); /// @notice returns true if a claim can be calculated by anyone function canClaimBeCalculatedByAnyone(uint256 index) external view returns (bool); /// @notice returns true if this claim is pending or awaiting function isClaimPending(uint256 index) external view returns (bool); /// @notice returns how many claims the holder has function countPolicyClaimerClaims(address user) external view returns (uint256); /// @notice returns how many pending claims are there function countPendingClaims() external view returns (uint256); /// @notice returns how many claims are there function countClaims() external view returns (uint256); /// @notice returns a claim index of it's claimer and an ordinal number function claimOfOwnerIndexAt(address claimer, uint256 orderIndex) external view returns (uint256); /// @notice returns pending claim index by its ordinal index function pendingClaimIndexAt(uint256 orderIndex) external view returns (uint256); /// @notice returns claim index by its ordinal index function claimIndexAt(uint256 orderIndex) external view returns (uint256); /// @notice returns current active claim index by policybook and claimer function claimIndex(address claimer, address policyBookAddress) external view returns (uint256); /// @notice returns true if the claim is appealed function isClaimAppeal(uint256 index) external view returns (bool); /// @notice returns current status of a claim function policyStatus(address claimer, address policyBookAddress) external view returns (ClaimStatus); /// @notice returns current status of a claim function claimStatus(uint256 index) external view returns (ClaimStatus); /// @notice returns the claim owner (claimer) function claimOwner(uint256 index) external view returns (address); /// @notice returns the claim PolicyBook function claimPolicyBook(uint256 index) external view returns (address); /// @notice returns claim info by its index function claimInfo(uint256 index) external view returns (ClaimInfo memory _claimInfo); function getAllPendingClaimsAmount() external view returns (uint256 _totalClaimsAmount); function getClaimableAmounts(uint256[] memory _claimIndexes) external view returns (uint256); /// @notice marks the user's claim as Accepted function acceptClaim(uint256 index) external; /// @notice marks the user's claim as Rejected function rejectClaim(uint256 index) external; /// @notice Update Image Uri in case it contains material that is ilegal /// or offensive. /// @dev Only the owner of the PolicyBookAdmin can erase/update evidenceUri. /// @param _claimIndex Claim Index that is going to be updated /// @param _newEvidenceURI New evidence uri. It can be blank. function updateImageUriOfClaim(uint256 _claimIndex, string calldata _newEvidenceURI) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "../interfaces/IContractsRegistry.sol"; abstract contract AbstractDependant { /// @dev keccak256(AbstractDependant.setInjector(address)) - 1 bytes32 private constant _INJECTOR_SLOT = 0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76; modifier onlyInjectorOrZero() { address _injector = injector(); require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector"); _; } function setInjector(address _injector) external onlyInjectorOrZero { bytes32 slot = _INJECTOR_SLOT; assembly { sstore(slot, _injector) } } /// @dev has to apply onlyInjectorOrZero() modifier function setDependencies(IContractsRegistry) external virtual; function injector() public view returns (address _injector) { bytes32 slot = _INJECTOR_SLOT; assembly { _injector := sload(slot) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds uint256 constant DAYS_IN_THE_YEAR = 365; uint256 constant MAX_INT = type(uint256).max; uint256 constant DECIMALS18 = 10**18; uint256 constant PRECISION = 10**25; uint256 constant PERCENTAGE_100 = 100 * PRECISION; uint256 constant BLOCKS_PER_DAY = 6450; uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365; uint256 constant APY_TOKENS = DECIMALS18; uint256 constant PROTOCOL_PERCENTAGE = 20 * PRECISION; uint256 constant DEFAULT_REBALANCING_THRESHOLD = 10**23; uint256 constant REBALANCE_DURATION = 1 days; uint256 constant EPOCH_DAYS_AMOUNT = 7;
SPDX-License-Identifier: MIT
interface IClaimingRegistry { function targetUR() external view returns (uint256); function d_ProtocolConstant() external view returns (uint256); function a_ProtocolConstant() external view returns (uint256); function a2_ProtocolConstant() external view returns (uint256); function max_ProtocolConstant() external view returns (uint256); function deployLeverageStableToCoveragePools(LeveragePortfolio leveragePoolType) external returns (uint256); function deployVirtualStableToCoveragePools() external returns (uint256); function setRebalancingThreshold(uint256 threshold) external; function setProtocolConstant( uint256 _targetUR, uint256 _d_ProtocolConstant, uint256 _a1_ProtocolConstant, uint256 _a2_ProtocolConstant, uint256 _max_ProtocolConstant ) external; function totalLiquidity() external view returns (uint256); function addPolicyPremium(uint256 epochsNumber, uint256 premiumAmount) external; function listleveragedCoveragePools(uint256 offset, uint256 limit) external view returns (address[] memory _coveragePools); function countleveragedCoveragePools() external view returns (uint256); } pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; } pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; enum ClaimStatus { CAN_CLAIM, UNCLAIMABLE, PENDING, AWAITING_CALCULATION, REJECTED_CAN_APPEAL, REJECTED, ACCEPTED } struct ClaimInfo { address claimer; address policyBookAddress; string evidenceURI; uint256 dateSubmitted; uint256 dateEnded; bool appeal; ClaimStatus status; uint256 claimAmount; } }
6,890,399
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 9762, 310, 4243, 288, 203, 565, 445, 1018, 1099, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 302, 67, 5752, 6902, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 279, 67, 5752, 6902, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 279, 22, 67, 5752, 6902, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 943, 67, 5752, 6902, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 7286, 1682, 5682, 30915, 774, 9739, 16639, 12, 1682, 5682, 17163, 884, 5682, 2864, 559, 13, 203, 3639, 3903, 203, 3639, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 7286, 6466, 30915, 774, 9739, 16639, 1435, 3903, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 444, 426, 28867, 7614, 12, 11890, 5034, 5573, 13, 3903, 31, 203, 203, 565, 445, 444, 5752, 6902, 12, 203, 3639, 2254, 5034, 389, 3299, 1099, 16, 203, 3639, 2254, 5034, 389, 72, 67, 5752, 6902, 16, 203, 3639, 2254, 5034, 389, 69, 21, 67, 5752, 6902, 16, 203, 3639, 2254, 5034, 389, 69, 22, 67, 5752, 6902, 16, 203, 3639, 2254, 5034, 389, 1896, 67, 5752, 6902, 203, 565, 262, 3903, 31, 203, 203, 203, 565, 445, 2078, 48, 18988, 24237, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 527, 2582, 23890, 5077, 12, 11890, 5034, 25480, 1854, 16, 2254, 5034, 23020, 5077, 6275, 13, 3903, 31, 203, 203, 565, 445, 666, 298, 502, 2 ]
pragma solidity ^0.4.21; /* Owned contract interface */ contract IOwned { // this function isn't abstract since the compiler emits automatically generated getter functions as external function owner() public view returns (address) {} function transferOwnership(address _newOwner) public; function acceptOwnership() public; } /* Bancor Formula interface */ contract IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256); function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256); } /* Contract Registry interface */ contract IContractRegistry { function getAddress(bytes32 _contractName) public view returns (address); } /* Contract Features interface */ contract IContractFeatures { function isSupported(address _contract, uint256 _features) public view returns (bool); function enableFeatures(uint256 _features, bool _enable) public; } /* Whitelist interface */ contract IWhitelist { function isWhitelisted(address _address) public view returns (bool); } /* ERC20 Standard Token interface */ contract IERC20Token { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public view returns (string) {} function symbol() public view returns (string) {} function decimals() public view returns (uint8) {} function totalSupply() public view returns (uint256) {} function balanceOf(address _owner) public view returns (uint256) { _owner; } function allowance(address _owner, address _spender) public view returns (uint256) { _owner; _spender; } function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); } /* Smart Token interface */ contract ISmartToken is IOwned, IERC20Token { function disableTransfers(bool _disable) public; function issue(address _to, uint256 _amount) public; function destroy(address _from, uint256 _amount) public; } /* Bancor Network interface */ contract IBancorNetwork { function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256); function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public payable returns (uint256); function convertForPrioritized( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s) public payable returns (uint256); } /* Token Holder interface */ contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; } /* Utilities & Common Modifiers */ contract Utils { /** constructor */ function Utils() public { } // verifies that an amount is greater than zero modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != address(0)); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } // 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; 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) { 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; assert(_x == 0 || z / _x == _y); return z; } } /* Provides support and utilities for contract ownership */ contract Owned is IOwned { address public owner; address public newOwner; event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** @dev constructor */ function Owned() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { assert(msg.sender == owner); _; } /** @dev allows transferring the contract ownership the new owner still needs to accept the transfer can only be called by the contract owner @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public ownerOnly { require(_newOwner != owner); newOwner = _newOwner; } /** @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } /* Provides support and utilities for contract management Note that a managed contract must also have an owner */ contract Managed is Owned { address public manager; address public newManager; event ManagerUpdate(address indexed _prevManager, address indexed _newManager); /** @dev constructor */ function Managed() public { manager = msg.sender; } // allows execution by the manager only modifier managerOnly { assert(msg.sender == manager); _; } // allows execution by either the owner or the manager only modifier ownerOrManagerOnly { require(msg.sender == owner || msg.sender == manager); _; } /** @dev allows transferring the contract management the new manager still needs to accept the transfer can only be called by the contract manager @param _newManager new contract manager */ function transferManagement(address _newManager) public ownerOrManagerOnly { require(_newManager != manager); newManager = _newManager; } /** @dev used by a new manager to accept a management transfer */ function acceptManagement() public { require(msg.sender == newManager); emit ManagerUpdate(manager, newManager); manager = newManager; newManager = address(0); } } /** Id definitions for bancor contracts Can be used in conjunction with the contract registry to get contract addresses */ contract ContractIds { bytes32 public constant BANCOR_NETWORK = "BancorNetwork"; bytes32 public constant BANCOR_FORMULA = "BancorFormula"; bytes32 public constant CONTRACT_FEATURES = "ContractFeatures"; } /** Id definitions for bancor contract features Can be used to query the ContractFeatures contract to check whether a certain feature is supported by a contract */ contract FeatureIds { // converter features uint256 public constant CONVERTER_CONVERSION_WHITELIST = 1 << 0; } /* We consider every contract to be a 'token holder' since it's currently not possible for a contract to deny receiving tokens. The TokenHolder's contract sole purpose is to provide a safety mechanism that allows the owner to send tokens that were sent to the contract by mistake back to their sender. */ contract TokenHolder is ITokenHolder, Owned, Utils { /** @dev constructor */ function TokenHolder() public { } /** @dev withdraws tokens held by the contract and sends them to an account can only be called by the owner @param _token ERC20 token contract address @param _to account to receive the new amount @param _amount amount to withdraw */ function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public ownerOnly validAddress(_token) validAddress(_to) notThis(_to) { assert(_token.transfer(_to, _amount)); } } /* The smart token controller is an upgradable part of the smart token that allows more functionality as well as fixes for bugs/exploits. Once it accepts ownership of the token, it becomes the token's sole controller that can execute any of its functions. To upgrade the controller, ownership must be transferred to a new controller, along with any relevant data. The smart token must be set on construction and cannot be changed afterwards. Wrappers are provided (as opposed to a single 'execute' function) for each of the token's functions, for easier access. Note that the controller can transfer token ownership to a new controller that doesn't allow executing any function on the token, for a trustless solution. Doing that will also remove the owner's ability to upgrade the controller. */ contract SmartTokenController is TokenHolder { ISmartToken public token; // smart token /** @dev constructor */ function SmartTokenController(ISmartToken _token) public validAddress(_token) { token = _token; } // ensures that the controller is the token's owner modifier active() { assert(token.owner() == address(this)); _; } // ensures that the controller is not the token's owner modifier inactive() { assert(token.owner() != address(this)); _; } /** @dev allows transferring the token ownership the new owner still need to accept the transfer can only be called by the contract owner @param _newOwner new token owner */ function transferTokenOwnership(address _newOwner) public ownerOnly { token.transferOwnership(_newOwner); } /** @dev used by a new owner to accept a token ownership transfer can only be called by the contract owner */ function acceptTokenOwnership() public ownerOnly { token.acceptOwnership(); } /** @dev disables/enables token transfers can only be called by the contract owner @param _disable true to disable transfers, false to enable them */ function disableTokenTransfers(bool _disable) public ownerOnly { token.disableTransfers(_disable); } /** @dev withdraws tokens held by the controller and sends them to an account can only be called by the owner @param _token ERC20 token contract address @param _to account to receive the new amount @param _amount amount to withdraw */ function withdrawFromToken( IERC20Token _token, address _to, uint256 _amount ) public ownerOnly { ITokenHolder(token).withdrawTokens(_token, _to, _amount); } } /* Bancor Converter interface */ contract IBancorConverter { function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256); function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256); function conversionWhitelist() public view returns (IWhitelist) {} // deprecated, backward compatibility function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256); } /* Bancor Converter v0.9 The Bancor version of the token converter, allows conversion between a smart token and other ERC20 tokens and between different ERC20 tokens and themselves. ERC20 connector balance can be virtual, meaning that the calculations are based on the virtual balance instead of relying on the actual connector balance. This is a security mechanism that prevents the need to keep a very large (and valuable) balance in a single contract. The converter is upgradable (just like any SmartTokenController). WARNING: It is NOT RECOMMENDED to use the converter with Smart Tokens that have less than 8 decimal digits or with very small numbers because of precision loss Open issues: - Front-running attacks are currently mitigated by the following mechanisms: - minimum return argument for each conversion provides a way to define a minimum/maximum price for the transaction - gas price limit prevents users from having control over the order of execution - gas price limit check can be skipped if the transaction comes from a trusted, whitelisted signer Other potential solutions might include a commit/reveal based schemes - Possibly add getters for the connector fields so that the client won't need to rely on the order in the struct */ contract BancorConverter is IBancorConverter, SmartTokenController, Managed, ContractIds, FeatureIds { uint32 private constant MAX_WEIGHT = 1000000; uint64 private constant MAX_CONVERSION_FEE = 1000000; struct Connector { uint256 virtualBalance; // connector virtual balance uint32 weight; // connector weight, represented in ppm, 1-1000000 bool isVirtualBalanceEnabled; // true if virtual balance is enabled, false if not bool isPurchaseEnabled; // is purchase of the smart token enabled with the connector, can be set by the owner bool isSet; // used to tell if the mapping element is defined } string public version = '0.9'; string public converterType = 'bancor'; IContractRegistry public registry; // contract registry contract IWhitelist public conversionWhitelist; // whitelist contract with list of addresses that are allowed to use the converter IERC20Token[] public connectorTokens; // ERC20 standard token addresses IERC20Token[] public quickBuyPath; // conversion path that's used in order to buy the token with ETH mapping (address => Connector) public connectors; // connector token addresses -> connector data uint32 private totalConnectorWeight = 0; // used to efficiently prevent increasing the total connector weight above 100% uint32 public maxConversionFee = 0; // maximum conversion fee for the lifetime of the contract, // represented in ppm, 0...1000000 (0 = no fee, 100 = 0.01%, 1000000 = 100%) uint32 public conversionFee = 0; // current conversion fee, represented in ppm, 0...maxConversionFee bool public conversionsEnabled = true; // true if token conversions is enabled, false if not IERC20Token[] private convertPath; // triggered when a conversion between two tokens occurs event Conversion( address indexed _fromToken, address indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return, int256 _conversionFee ); // triggered after a conversion with new price data event PriceDataUpdate( address indexed _connectorToken, uint256 _tokenSupply, uint256 _connectorBalance, uint32 _connectorWeight ); // triggered when the conversion fee is updated event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee); /** @dev constructor @param _token smart token governed by the converter @param _registry address of a contract registry contract @param _maxConversionFee maximum conversion fee, represented in ppm @param _connectorToken optional, initial connector, allows defining the first connector at deployment time @param _connectorWeight optional, weight for the initial connector */ function BancorConverter( ISmartToken _token, IContractRegistry _registry, uint32 _maxConversionFee, IERC20Token _connectorToken, uint32 _connectorWeight ) public SmartTokenController(_token) validAddress(_registry) validMaxConversionFee(_maxConversionFee) { registry = _registry; IContractFeatures features = IContractFeatures(registry.getAddress(ContractIds.CONTRACT_FEATURES)); // initialize supported features if (features != address(0)) features.enableFeatures(FeatureIds.CONVERTER_CONVERSION_WHITELIST, true); maxConversionFee = _maxConversionFee; if (_connectorToken != address(0)) addConnector(_connectorToken, _connectorWeight, false); } // validates a connector token address - verifies that the address belongs to one of the connector tokens modifier validConnector(IERC20Token _address) { require(connectors[_address].isSet); _; } // validates a token address - verifies that the address belongs to one of the convertible tokens modifier validToken(IERC20Token _address) { require(_address == token || connectors[_address].isSet); _; } // validates maximum conversion fee modifier validMaxConversionFee(uint32 _conversionFee) { require(_conversionFee >= 0 && _conversionFee <= MAX_CONVERSION_FEE); _; } // validates conversion fee modifier validConversionFee(uint32 _conversionFee) { require(_conversionFee >= 0 && _conversionFee <= maxConversionFee); _; } // validates connector weight range modifier validConnectorWeight(uint32 _weight) { require(_weight > 0 && _weight <= MAX_WEIGHT); _; } // validates a conversion path - verifies that the number of elements is odd and that maximum number of 'hops' is 10 modifier validConversionPath(IERC20Token[] _path) { require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1); _; } // allows execution only when conversions aren't disabled modifier conversionsAllowed { assert(conversionsEnabled); _; } // allows execution by the BancorNetwork contract only modifier bancorNetworkOnly { IBancorNetwork bancorNetwork = IBancorNetwork(registry.getAddress(ContractIds.BANCOR_NETWORK)); require(msg.sender == address(bancorNetwork)); _; } /** @dev returns the number of connector tokens defined @return number of connector tokens */ function connectorTokenCount() public view returns (uint16) { return uint16(connectorTokens.length); } /* @dev allows the owner to update the registry contract address @param _registry address of a bancor converter registry contract */ function setRegistry(IContractRegistry _registry) public ownerOnly validAddress(_registry) notThis(_registry) { registry = _registry; } /* @dev allows the owner to update & enable the conversion whitelist contract address when set, only addresses that are whitelisted are actually allowed to use the converter note that the whitelist check is actually done by the BancorNetwork contract @param _whitelist address of a whitelist contract */ function setConversionWhitelist(IWhitelist _whitelist) public ownerOnly notThis(_whitelist) { conversionWhitelist = _whitelist; } /* @dev allows the manager to update the quick buy path @param _path new quick buy path, see conversion path format in the bancorNetwork contract */ function setQuickBuyPath(IERC20Token[] _path) public ownerOnly validConversionPath(_path) { quickBuyPath = _path; } /* @dev allows the manager to clear the quick buy path */ function clearQuickBuyPath() public ownerOnly { quickBuyPath.length = 0; } /** @dev returns the length of the quick buy path array @return quick buy path length */ function getQuickBuyPathLength() public view returns (uint256) { return quickBuyPath.length; } /** @dev disables the entire conversion functionality this is a safety mechanism in case of a emergency can only be called by the manager @param _disable true to disable conversions, false to re-enable them */ function disableConversions(bool _disable) public ownerOrManagerOnly { conversionsEnabled = !_disable; } /** @dev updates the current conversion fee can only be called by the manager @param _conversionFee new conversion fee, represented in ppm */ function setConversionFee(uint32 _conversionFee) public ownerOrManagerOnly validConversionFee(_conversionFee) { emit ConversionFeeUpdate(conversionFee, _conversionFee); conversionFee = _conversionFee; } /* @dev given a return amount, returns the amount minus the conversion fee @param _amount return amount @param _magnitude 1 for standard conversion, 2 for cross connector conversion @return return amount minus conversion fee */ function getFinalAmount(uint256 _amount, uint8 _magnitude) public view returns (uint256) { return safeMul(_amount, (MAX_CONVERSION_FEE - conversionFee) ** _magnitude) / MAX_CONVERSION_FEE ** _magnitude; } /** @dev defines a new connector for the token can only be called by the owner while the converter is inactive @param _token address of the connector token @param _weight constant connector weight, represented in ppm, 1-1000000 @param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it */ function addConnector(IERC20Token _token, uint32 _weight, bool _enableVirtualBalance) public ownerOnly inactive validAddress(_token) notThis(_token) validConnectorWeight(_weight) { require(_token != token && !connectors[_token].isSet && totalConnectorWeight + _weight <= MAX_WEIGHT); // validate input connectors[_token].virtualBalance = 0; connectors[_token].weight = _weight; connectors[_token].isVirtualBalanceEnabled = _enableVirtualBalance; connectors[_token].isPurchaseEnabled = true; connectors[_token].isSet = true; connectorTokens.push(_token); totalConnectorWeight += _weight; } /** @dev updates one of the token connectors can only be called by the owner @param _connectorToken address of the connector token @param _weight constant connector weight, represented in ppm, 1-1000000 @param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it @param _virtualBalance new connector's virtual balance */ function updateConnector(IERC20Token _connectorToken, uint32 _weight, bool _enableVirtualBalance, uint256 _virtualBalance) public ownerOnly validConnector(_connectorToken) validConnectorWeight(_weight) { Connector storage connector = connectors[_connectorToken]; require(totalConnectorWeight - connector.weight + _weight <= MAX_WEIGHT); // validate input totalConnectorWeight = totalConnectorWeight - connector.weight + _weight; connector.weight = _weight; connector.isVirtualBalanceEnabled = _enableVirtualBalance; connector.virtualBalance = _virtualBalance; } /** @dev disables purchasing with the given connector token in case the connector token got compromised can only be called by the owner note that selling is still enabled regardless of this flag and it cannot be disabled by the owner @param _connectorToken connector token contract address @param _disable true to disable the token, false to re-enable it */ function disableConnectorPurchases(IERC20Token _connectorToken, bool _disable) public ownerOnly validConnector(_connectorToken) { connectors[_connectorToken].isPurchaseEnabled = !_disable; } /** @dev returns the connector's virtual balance if one is defined, otherwise returns the actual balance @param _connectorToken connector token contract address @return connector balance */ function getConnectorBalance(IERC20Token _connectorToken) public view validConnector(_connectorToken) returns (uint256) { Connector storage connector = connectors[_connectorToken]; return connector.isVirtualBalanceEnabled ? connector.virtualBalance : _connectorToken.balanceOf(this); } /** @dev returns the expected return for converting a specific amount of _fromToken to _toToken @param _fromToken ERC20 token to convert from @param _toToken ERC20 token to convert to @param _amount amount to convert, in fromToken @return expected conversion return amount */ function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256) { require(_fromToken != _toToken); // validate input // conversion between the token and one of its connectors if (_toToken == token) return getPurchaseReturn(_fromToken, _amount); else if (_fromToken == token) return getSaleReturn(_toToken, _amount); // conversion between 2 connectors return getCrossConnectorReturn(_fromToken, _toToken, _amount); } /** @dev returns the expected return for buying the token for a connector token @param _connectorToken connector token contract address @param _depositAmount amount to deposit (in the connector token) @return expected purchase return amount */ function getPurchaseReturn(IERC20Token _connectorToken, uint256 _depositAmount) public view active validConnector(_connectorToken) returns (uint256) { Connector storage connector = connectors[_connectorToken]; require(connector.isPurchaseEnabled); // validate input uint256 tokenSupply = token.totalSupply(); uint256 connectorBalance = getConnectorBalance(_connectorToken); IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA)); uint256 amount = formula.calculatePurchaseReturn(tokenSupply, connectorBalance, connector.weight, _depositAmount); // return the amount minus the conversion fee return getFinalAmount(amount, 1); } /** @dev returns the expected return for selling the token for one of its connector tokens @param _connectorToken connector token contract address @param _sellAmount amount to sell (in the smart token) @return expected sale return amount */ function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount) public view active validConnector(_connectorToken) returns (uint256) { Connector storage connector = connectors[_connectorToken]; uint256 tokenSupply = token.totalSupply(); uint256 connectorBalance = getConnectorBalance(_connectorToken); IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA)); uint256 amount = formula.calculateSaleReturn(tokenSupply, connectorBalance, connector.weight, _sellAmount); // return the amount minus the conversion fee return getFinalAmount(amount, 1); } /** @dev returns the expected return for selling one of the connector tokens for another connector token @param _fromConnectorToken contract address of the connector token to convert from @param _toConnectorToken contract address of the connector token to convert to @param _sellAmount amount to sell (in the from connector token) @return expected sale return amount (in the to connector token) */ function getCrossConnectorReturn(IERC20Token _fromConnectorToken, IERC20Token _toConnectorToken, uint256 _sellAmount) public view active validConnector(_fromConnectorToken) validConnector(_toConnectorToken) returns (uint256) { Connector storage fromConnector = connectors[_fromConnectorToken]; Connector storage toConnector = connectors[_toConnectorToken]; require(toConnector.isPurchaseEnabled); // validate input uint256 fromConnectorBalance = getConnectorBalance(_fromConnectorToken); uint256 toConnectorBalance = getConnectorBalance(_toConnectorToken); IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA)); uint256 amount = formula.calculateCrossConnectorReturn(fromConnectorBalance, fromConnector.weight, toConnectorBalance, toConnector.weight, _sellAmount); // return the amount minus the conversion fee // the fee is higher (magnitude = 2) since cross connector conversion equals 2 conversions (from / to the smart token) return getFinalAmount(amount, 2); } /** @dev converts a specific amount of _fromToken to _toToken @param _fromToken ERC20 token to convert from @param _toToken ERC20 token to convert to @param _amount amount to convert, in fromToken @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return conversion return amount */ function convertInternal(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public bancorNetworkOnly conversionsAllowed greaterThanZero(_minReturn) returns (uint256) { require(_fromToken != _toToken); // validate input // conversion between the token and one of its connectors if (_toToken == token) return buy(_fromToken, _amount, _minReturn); else if (_fromToken == token) return sell(_toToken, _amount, _minReturn); // conversion between 2 connectors uint256 amount = getCrossConnectorReturn(_fromToken, _toToken, _amount); // ensure the trade gives something in return and meets the minimum requested amount require(amount != 0 && amount >= _minReturn); // update the source token virtual balance if relevant Connector storage fromConnector = connectors[_fromToken]; if (fromConnector.isVirtualBalanceEnabled) fromConnector.virtualBalance = safeAdd(fromConnector.virtualBalance, _amount); // update the target token virtual balance if relevant Connector storage toConnector = connectors[_toToken]; if (toConnector.isVirtualBalanceEnabled) toConnector.virtualBalance = safeSub(toConnector.virtualBalance, amount); // ensure that the trade won't deplete the connector balance uint256 toConnectorBalance = getConnectorBalance(_toToken); assert(amount < toConnectorBalance); // transfer funds from the caller in the from connector token assert(_fromToken.transferFrom(msg.sender, this, _amount)); // transfer funds to the caller in the to connector token // the transfer might fail if the actual connector balance is smaller than the virtual balance assert(_toToken.transfer(msg.sender, amount)); // calculate conversion fee and dispatch the conversion event // the fee is higher (magnitude = 2) since cross connector conversion equals 2 conversions (from / to the smart token) uint256 feeAmount = safeSub(amount, getFinalAmount(amount, 2)); dispatchConversionEvent(_fromToken, _toToken, _amount, amount, feeAmount); // dispatch price data updates for the smart token / both connectors emit PriceDataUpdate(_fromToken, token.totalSupply(), getConnectorBalance(_fromToken), fromConnector.weight); emit PriceDataUpdate(_toToken, token.totalSupply(), getConnectorBalance(_toToken), toConnector.weight); return amount; } /** @dev converts a specific amount of _fromToken to _toToken @param _fromToken ERC20 token to convert from @param _toToken ERC20 token to convert to @param _amount amount to convert, in fromToken @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return conversion return amount */ function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) { convertPath = [_fromToken, token, _toToken]; return quickConvert(convertPath, _amount, _minReturn); } /** @dev buys the token by depositing one of its connector tokens @param _connectorToken connector token contract address @param _depositAmount amount to deposit (in the connector token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return buy return amount */ function buy(IERC20Token _connectorToken, uint256 _depositAmount, uint256 _minReturn) internal returns (uint256) { uint256 amount = getPurchaseReturn(_connectorToken, _depositAmount); // ensure the trade gives something in return and meets the minimum requested amount require(amount != 0 && amount >= _minReturn); // update virtual balance if relevant Connector storage connector = connectors[_connectorToken]; if (connector.isVirtualBalanceEnabled) connector.virtualBalance = safeAdd(connector.virtualBalance, _depositAmount); // transfer funds from the caller in the connector token assert(_connectorToken.transferFrom(msg.sender, this, _depositAmount)); // issue new funds to the caller in the smart token token.issue(msg.sender, amount); // calculate conversion fee and dispatch the conversion event uint256 feeAmount = safeSub(amount, getFinalAmount(amount, 1)); dispatchConversionEvent(_connectorToken, token, _depositAmount, amount, feeAmount); // dispatch price data update for the smart token/connector emit PriceDataUpdate(_connectorToken, token.totalSupply(), getConnectorBalance(_connectorToken), connector.weight); return amount; } /** @dev sells the token by withdrawing from one of its connector tokens @param _connectorToken connector token contract address @param _sellAmount amount to sell (in the smart token) @param _minReturn if the conversion results in an amount smaller the minimum return - it is cancelled, must be nonzero @return sell return amount */ function sell(IERC20Token _connectorToken, uint256 _sellAmount, uint256 _minReturn) internal returns (uint256) { require(_sellAmount <= token.balanceOf(msg.sender)); // validate input uint256 amount = getSaleReturn(_connectorToken, _sellAmount); // ensure the trade gives something in return and meets the minimum requested amount require(amount != 0 && amount >= _minReturn); // ensure that the trade will only deplete the connector balance if the total supply is depleted as well uint256 tokenSupply = token.totalSupply(); uint256 connectorBalance = getConnectorBalance(_connectorToken); assert(amount < connectorBalance || (amount == connectorBalance && _sellAmount == tokenSupply)); // update virtual balance if relevant Connector storage connector = connectors[_connectorToken]; if (connector.isVirtualBalanceEnabled) connector.virtualBalance = safeSub(connector.virtualBalance, amount); // destroy _sellAmount from the caller's balance in the smart token token.destroy(msg.sender, _sellAmount); // transfer funds to the caller in the connector token // the transfer might fail if the actual connector balance is smaller than the virtual balance assert(_connectorToken.transfer(msg.sender, amount)); // calculate conversion fee and dispatch the conversion event uint256 feeAmount = safeSub(amount, getFinalAmount(amount, 1)); dispatchConversionEvent(token, _connectorToken, _sellAmount, amount, feeAmount); // dispatch price data update for the smart token/connector emit PriceDataUpdate(_connectorToken, token.totalSupply(), getConnectorBalance(_connectorToken), connector.weight); return amount; } /** @dev converts the token to any other token in the bancor network by following a predefined conversion path note that when converting from an ERC20 token (as opposed to a smart token), allowance must be set beforehand @param _path conversion path, see conversion path format in the BancorNetwork contract @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return tokens issued in return */ function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable validConversionPath(_path) returns (uint256) { return quickConvertPrioritized(_path, _amount, _minReturn, 0x0, 0x0, 0x0, 0x0); } /** @dev converts the token to any other token in the bancor network by following a predefined conversion path note that when converting from an ERC20 token (as opposed to a smart token), allowance must be set beforehand @param _path conversion path, see conversion path format in the BancorNetwork contract @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _block if the current block exceeded the given parameter - it is cancelled @param _v (signature[128:130]) associated with the signer address and helps validating if the signature is legit @param _r (signature[0:64]) associated with the signer address and helps validating if the signature is legit @param _s (signature[64:128]) associated with the signer address and helps validating if the signature is legit @return tokens issued in return */ function quickConvertPrioritized(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s) public payable validConversionPath(_path) returns (uint256) { IERC20Token fromToken = _path[0]; IBancorNetwork bancorNetwork = IBancorNetwork(registry.getAddress(ContractIds.BANCOR_NETWORK)); // we need to transfer the source tokens from the caller to the BancorNetwork contract, // so it can execute the conversion on behalf of the caller if (msg.value == 0) { // not ETH, send the source tokens to the BancorNetwork contract // if the token is the smart token, no allowance is required - destroy the tokens // from the caller and issue them to the BancorNetwork contract if (fromToken == token) { token.destroy(msg.sender, _amount); // destroy _amount tokens from the caller's balance in the smart token token.issue(bancorNetwork, _amount); // issue _amount new tokens to the BancorNetwork contract } else { // otherwise, we assume we already have allowance, transfer the tokens directly to the BancorNetwork contract assert(fromToken.transferFrom(msg.sender, bancorNetwork, _amount)); } } // execute the conversion and pass on the ETH with the call return bancorNetwork.convertForPrioritized.value(msg.value)(_path, _amount, _minReturn, msg.sender, _block, _v, _r, _s); } // deprecated, backward compatibility function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) { return convertInternal(_fromToken, _toToken, _amount, _minReturn); } /** @dev helper, dispatches the Conversion event @param _fromToken ERC20 token to convert from @param _toToken ERC20 token to convert to @param _amount amount purchased/sold (in the source token) @param _returnAmount amount returned (in the target token) */ function dispatchConversionEvent(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _returnAmount, uint256 _feeAmount) private { // fee amount is converted to 255 bits - // negative amount means the fee is taken from the source token, positive amount means its taken from the target token // currently the fee is always taken from the target token // since we convert it to a signed number, we first ensure that it's capped at 255 bits to prevent overflow assert(_feeAmount <= 2 ** 255); emit Conversion(_fromToken, _toToken, msg.sender, _amount, _returnAmount, int256(_feeAmount)); } /** @dev fallback, buys the smart token with ETH note that the purchase will use the price at the time of the purchase */ function() payable public { quickConvert(quickBuyPath, msg.value, 1); } } /* Bancor Converter Factory interface */ contract IBancorConverterFactory { function createConverter( ISmartToken _token, IContractRegistry _registry, uint32 _maxConversionFee, IERC20Token _connectorToken, uint32 _connectorWeight ) public returns (address); } /* Bancor Converter Factory */ contract BancorConverterFactory is IBancorConverterFactory { // triggered when a new converter is created event NewConverter(address indexed _converter, address indexed _owner); /** @dev constructor */ function BancorConverterFactory() public { } /** @dev creates a new converter with the given arguments and transfers the ownership and management to the sender. @param _token smart token governed by the converter @param _registry address of a contract registry contract @param _maxConversionFee maximum conversion fee, represented in ppm @param _connectorToken optional, initial connector, allows defining the first connector at deployment time @param _connectorWeight optional, weight for the initial connector @return a new converter */ function createConverter( ISmartToken _token, IContractRegistry _registry, uint32 _maxConversionFee, IERC20Token _connectorToken, uint32 _connectorWeight ) public returns(address converterAddress) { BancorConverter converter = new BancorConverter( _token, _registry, _maxConversionFee, _connectorToken, _connectorWeight ); converter.transferOwnership(msg.sender); converter.transferManagement(msg.sender); address _converterAddress = address(converter); emit NewConverter(_converterAddress, msg.sender); return _converterAddress; } }
destroy _amount tokens from the caller's balance in the smart token
token.destroy(msg.sender, _amount);
14,559
[ 1, 11662, 389, 8949, 2430, 628, 326, 4894, 1807, 11013, 316, 326, 13706, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 7734, 1147, 18, 11662, 12, 3576, 18, 15330, 16, 389, 8949, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.22; import "./zeppelin-solidity/contracts/math/SafeMath.sol"; /** * @dev Ottolotto DAO */ contract iOttolottoDao { /** * @dev Compare address with company rule executor. */ function onlyCompany(address) public view returns (bool) {} } /** * @dev Ottolotto platform referral system interface. */ contract iReferralSystem { /** * @dev Create new referral */ function addReferral(address, address) public returns (bool) {} /** * @dev Get percent by referral system. */ function getPercent(address) public view returns (uint8) {} /** * @dev Get partner in referral system by referral address. */ function getPartner(address) public view returns (address) {} } /** * @title KingsLoto game * * In fact, it’s the most transparent and fair lottery in the world! * Player buys a ticket with cryptocurrency and chooses his 6 lucky numbers (from 0 to 15). * Twice a week (Tuesday and Friday) lottery should start from the block hash, * which was set in advance in the draw info. We’ll take the last number of each hash * (this is exactly that ball, which is used in the regular lottery). * Six hashes - six lucky numbers in the end. Then smart-contract is processing the draw * information and sends all prizes automatically to the winners' wallets! * One ticket plays twice - in regular lottery draw and in the Grand Jackpot draw on the 21st of December. * This means somebody will receive all money for sure! */ contract KingsLoto { using SafeMath for uint256; using SafeMath for uint8; /** * @dev Write info to log when the game was started. * * @param _game Started game. * @param _nextGame Next game number. */ event StartedGame(uint256 indexed _game, uint256 _nextGame); /** * @dev Write to log info about bets calculation progress. * * @param _game Processed game. * @param _processed A number of processed bets. * @param _toProcess Total of bets. */ event GameProgress(uint256 indexed _game, uint256 _processed, uint256 _toProcess); /** * @dev Write to log info about ticket selling. * * @param _game The game number on which ticket was sold. * @param _address Buyer address. * @param bet Player bet. */ event Ticket(uint256 indexed _game, address indexed _address, bytes3 bet); /** * @dev Write info to log about winner when calculating stats. * * @param _address Winner address. * @param _game A number of the game. * @param _matches A number of matches. * @param _bet Winning Bet. * @param _time Time of determining the winner. */ event Winning( address indexed _address, uint256 indexed _game, uint8 _matches, bytes3 _bet, uint256 _time ); /** * @dev Write info to log when the bet was paid. * * @param _address Address of the winner (recipient). * @param _game A number of the game. * @param _matches A number of matches. * @param _bet Winning Bet. * @param _amount Prize amount (in wei). * @param _time A time when the bet was paid. */ event BetPaid( address indexed _address, uint256 indexed _game, uint8 _matches, bytes3 _bet, uint256 _amount, uint256 _time ); /** * @dev Write info to log about jackpot winner. * * @param _address Address of the winner (recipient). * @param _game A number of the game. * @param _amount Prize amount (in wei). * @param _time Time of determining the jackpot winner. */ event Jackpot( address indexed _address, uint256 indexed _game, uint256 _amount, uint256 _time ); /** * @dev Write to log info about raised funds in referral system. * * @param _partner Address of the partner which get funds. * @param _referral Referral address. * @param _type Referral payment type (0x00 - ticket selling, 0x01 winnings in the game). * @param _game A number of the game. * @param _amount Raised funds amount by the partner. * @param _time A time when funds were sent to partner. */ event RaisedByPartner( address indexed _partner, address indexed _referral, bytes1 _type, uint256 _game, uint256 _amount, uint256 _time ); /** * @dev Write info to log about grand jackpot game starting. * * @param _game A number of the game. * @param _time A time when the game was started. */ event ChampionGameStarted(uint256 indexed _game, uint256 _time); /** * @dev Write info to log about the new player in the grand jackpot. * * @param _player Player address. * @param _game A number of the grand jackpot game. * @param _number Player number in the game. */ event ChampionPlayer(address indexed _player, uint256 indexed _game, uint256 _number); /** * @dev Write info to log about the winner in the grand jackpot. * * @param _winner Address of the winner. * @param _game A number of the game. * @param _number Player number in the game. * @param _jackpot Prize. * @param _time A time when the prize was sent to the winner. */ event ChampionWinner( address indexed _winner, uint256 indexed _game, uint256 _number, uint256 _jackpot, uint256 indexed _time ); /** * @dev Bet struct * contain info about the player bet. */ struct Bet { address player; bytes3 bet; } /** * @dev Winner struct * contain info about the winner. */ struct Winner { uint256 betIndex; uint8 matches; } /** * @dev Declares a state variable that stores game winners. */ mapping(uint256 => Winner[]) winners; /** * @dev Declares a state variable that stores game bets. */ mapping(uint256 => Bet[]) gameBets; /** * @dev Declares a state variable that stores game jackpots. */ mapping(uint256 => uint256) weiRaised; /** * @dev Declares a state variable that stores game start block. */ mapping(uint256 => uint256) gameStartBlock; /** * @dev Declares a state variable that stores calculated game stats. */ mapping(uint256 => uint32[7]) gameStats; /** * @dev Declares a state variable that stores game miscalculation status. */ mapping(uint256 => bool) gameCalculated; /** * @dev Declares a state variable that stores game calculation progress status. */ mapping(uint256 => uint256) gameCalculationProgress; /** * @dev Declares a state variable that stores bet payments progress. */ mapping(uint256 => uint256) betsPaymentsProgress; /** * @dev Declares a state variable that stores percentages for funds distribution. */ mapping(uint8 => uint8) percents; /** * @dev Declares a state variable that stores a last byte of the game blocks. */ mapping(uint256 => bytes1[6]) gameBlocks; /** * @dev Declares a state variable that stores a game jackpot, * if the jackpot is raised in this game. */ mapping(uint256 => uint256) raisedJackpots; /** * @dev First game interval in seconds. */ uint256 constant GAME_INTERVAL_ONE = 259200; /** * @dev Second game interval in seconds. */ uint256 constant GAME_INTERVAL_TWO = 345600; /** * @dev Last game start time. */ uint256 public gameStartedAt = 1524830400; /** * @dev Marks current lotto interval. */ bool public isFristInterval = false; /** * @dev Variable that store jackpot value. */ uint256 public jackpot; /** * @dev Next game number. */ uint256 public gameNext; /** * @dev Played game number. */ uint256 public gamePlayed; /** * @dev Lotto game duration in blocks. */ uint8 public gameDuration = 6; /** * @dev The interval which will be added to the start block number. */ uint8 public startBlockInterval = 12; /** * @dev Status of the played game (true if the game is in the process, false if the game is finished). */ bool public gamePlayedStatus = false; /** * @dev Ticket price. */ uint256 public ticketPrice = 0.001 ether; /** * @dev New ticket price for the next game. */ uint256 public newPrice = 0; // Stats of the Grand jackpot. /** * @dev Define constant which indicates rules. */ uint8 constant NUMBER = 1; /** * @dev Define constant which indicates rules. */ uint8 constant STRING = 0; /** * @dev Steps for calculation leap year. */ uint8 public leapYearStep = 2; /** * @dev Interval of the Grand jackpot game in the standard year. */ uint256 constant CHAMPION_GAME_INTERVAL_ONE = 31536000; /** * @dev Interval of the Grand jackpot game in the leap year. */ uint256 constant CHAMPION_GAME_INTERVAL_TWO = 31622400; /** * @dev Last start time for the Grand jackpot. */ uint256 public championGameStartedAt = 1482321600; /** * @dev A number of the next Grand jackpot game. */ uint256 public game = 0; /** * @dev A number of the current Grand jackpot game. */ uint256 public currentGameBlockNumber; /** * @dev Declares a state variable that stores game start block. */ mapping(uint256 => uint256) internal championGameStartBlock; /** * @dev Declares a state variable that stores game start block. */ mapping(uint256 => address[]) internal gamePlayers; /** * @dev Commission of the platform in this game. */ uint256 commission = 21; /** * @dev Ottolotto DAO instance. */ iOttolottoDao public dao; /** * @dev Ottolotto referral system instance. */ iReferralSystem public referralSystem; /** * @dev Initialize smart contract. */ constructor() public { gameNext = block.number; game = block.number; percents[1] = 5; percents[2] = 8; percents[3] = 12; percents[4] = 15; percents[5] = 25; percents[6] = 35; dao = iOttolottoDao(0x24643A6432721070943a389f0D6445FC3F57e18C); referralSystem = iReferralSystem(0x0BD15B6A36f6002AEe906ECdf73877387E66AF96); } /** * @dev Get game prize * * @param _game A number of the game. */ function getGamePrize(uint256 _game) public view returns (uint256) { return weiRaised[_game]; } /** * @dev Get game start block * * @param _game A number of the game. */ function getGameStartBlock(uint256 _game) public view returns (uint256) { return gameStartBlock[_game]; } /** * @dev Get game calculation progress. * * @param _game A number of the game. */ function getGameCalculationProgress(uint256 _game) public view returns (uint256) { return gameCalculationProgress[_game]; } /** * @dev Get players counts in the game. * * @param _game A number of the game. */ function getPlayersCount(uint256 _game) public view returns (uint256) { return gameBets[_game].length; } /** * @dev Get game calculated stats. * * @param _game A number of the game. */ function getGameCalculatedStats(uint256 _game) public view returns (uint32[7]) { return gameStats[_game]; } /** * @dev Get stored game blocks in the contract. * * @param _game A number of the game. */ function getStoredGameBlocks(uint256 _game) public view returns (bytes1[6]) { return gameBlocks[_game]; } /** * @dev Get bets payment progress. * * @param _game A number of the game. */ function getBetsPaymentsProgress(uint256 _game) public view returns (uint256) { return betsPaymentsProgress[_game]; } /** * @dev Check if bets are paid in the game. * * @param _game A number of the game. */ function betsArePayed(uint256 _game) public view returns (bool) { return betsPaymentsProgress[_game] == winners[_game].length; } /** * @dev Get current game interval. */ function getCurrentInterval() public view returns (uint256) { if (isFristInterval) { return GAME_INTERVAL_ONE; } return GAME_INTERVAL_TWO; } /** * @dev Get game target date. */ function targetDate() public view returns (uint256) { return gameStartedAt + getCurrentInterval(); } /** * @dev Change game interval. */ function toogleInterval() internal { uint256 interval = getCurrentInterval(); gameStartedAt += interval; isFristInterval = !isFristInterval; } /** * @dev Make bet function. * * @param _bet Player bet. * @param _partner Referral system partner address. */ function makeBet(bytes3 _bet, address _partner) public payable { require(msg.value == ticketPrice); gameBets[gameNext].push(Bet({player: msg.sender, bet: _bet})); uint256 reised = ticketPrice; address partner = referralSystem.getPartner(msg.sender); if (_partner != 0x0 || partner != 0x0) { if (partner == 0x0) { referralSystem.addReferral(msg.sender, _partner); partner = _partner; } uint8 percent = referralSystem.getPercent(partner); uint256 toPartner = reised.mul(percent).div(100); partner.transfer(toPartner); emit RaisedByPartner( partner, msg.sender, 0x00, gameNext, toPartner, now ); reised -= toPartner; } weiRaised[gameNext] += reised; emit Ticket(gameNext, msg.sender, _bet); buyChampionTicket(msg.sender); } /** * @dev Add a player to the Grand jackpot game. * * @param _player Player address. */ function buyChampionTicket(address _player) internal { gamePlayers[game].push(_player); emit ChampionPlayer( _player, currentGameBlockNumber, gamePlayers[game].length ); } /** * @dev Starting lotto game. */ function startGame() public { require(targetDate() <= now); gamePlayed = gameNext; gameNext = block.number; gamePlayedStatus = true; gameStartBlock[gamePlayed] = block.number + startBlockInterval; if (weiRaised[gamePlayed] != 0) { jackpot += weiRaised[gamePlayed].mul(percents[6]).div(100); } toogleInterval(); emit StartedGame(gamePlayed, gameNext); if (newPrice != 0) { ticketPrice = newPrice; newPrice = 0; } } /** * @dev Bitwise shifts for bet comparison. * * @param _bet Player bet. * @param _step Step. */ function bitwiseShifts(bytes3 _bet, uint8 _step) internal pure returns (bytes3) { return _bet >> (20 - (_step * 4)) << 20 >> 4; } /** * @dev Get matches in the bet. * * @param _game A number of the game. * @param _bet Bet. */ function getMatches(uint256 _game, bytes3 _bet) public view returns (uint8) { uint8 matches = 0; for (uint8 i = 0; i < gameDuration; i++) { if (gameBlocks[_game][i] ^ bitwiseShifts(_bet, i) == 0) { matches++; continue; } break; } return matches; } /** * @dev Get matches in the game. * * @param _game A number of the game. */ function getAllMatches(uint256 _game) public view returns (uint256[]) { uint256[] memory matches = new uint256[](7); for (uint32 i = 0; i < gameBets[_game].length; i++) { uint8 matched = getMatches(_game, gameBets[_game][i].bet); if (matched == 0) { continue; } matches[matched] += 1; } return matches; } /** * @dev Check if the game is over. * * @param _game A number of the game. */ function gameIsOver(uint256 _game) public view returns (bool) { if (gameStartBlock[_game] == 0) { return false; } return (gameStartBlock[_game] + gameDuration - 1) < block.number; } /** * @dev Check if the game is calculated. * * @param _game A number of the game. */ function gameIsCalculated(uint256 _game) public view returns (bool) { return gameCalculated[_game]; } /** * @dev Update game to calculated. * * @param _game A number of the game. */ function updateGameToCalculated(uint256 _game) internal { gameCalculated[_game] = true; gamePlayedStatus = false; } /** * @dev Init game blocks. * * @param _game A number of the game. * @param _startBlock A number of the start block. */ function initGameBlocks(uint256 _game,uint256 _startBlock) internal { for (uint8 i = 0; i < gameDuration; i++) { bytes32 blockHash = blockhash(_startBlock + i); gameBlocks[_game][i] = blockHash[31] << 4 >> 4; } } /** * @dev Process game. * * @param _game A number of the game. * @param _calculationStep Calculation step. */ function processGame(uint256 _game, uint256 _calculationStep) public returns (bool) { require(gameIsOver(_game)); if (gameIsCalculated(_game)) { return true; } if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); return true; } uint256 steps = _calculationStep; if (gameCalculationProgress[_game] + steps > gameBets[_game].length) { steps -= gameCalculationProgress[_game] + steps - gameBets[_game].length; } uint32[] memory matches = new uint32[](7); uint256 to = gameCalculationProgress[_game] + steps; uint256 startBlock = getGameStartBlock(_game); if (gameBlocks[_game][0] == 0x0) { initGameBlocks(_game, startBlock); } uint256 i = gameCalculationProgress[_game]; for (; i < to; i++) { uint8 matched = getMatches(_game, gameBets[_game][i].bet); if (matched == 0) { continue; } matches[matched] += 1; winners[_game].push( Winner({ betIndex: i, matches: matched }) ); emit Winning( gameBets[_game][i].player, _game, matched, gameBets[_game][i].bet, now ); } gameCalculationProgress[_game] += steps; for (i = 1; i <= 6; i++) { gameStats[_game][i] += matches[i]; } emit GameProgress(_game, gameCalculationProgress[_game], gameBets[_game].length); if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); distributeRaisedWeiToJackpot(_game); return true; } return false; } /** * @dev Distribute raised Wei to Jackpot if there are no matches. * * @param _game A number of the game. */ function distributeRaisedWeiToJackpot(uint256 _game) internal { for (uint8 i = 1; i <= 5; i ++) { if (gameStats[_game][i] == 0) { jackpot += weiRaised[_game].mul(percents[i]).div(100); } } } /** * @dev Change ticket price on the next game. * * @param _newPrice New ticket price. */ function changeTicketPrice(uint256 _newPrice) public { require(dao.onlyCompany(msg.sender)); newPrice = _newPrice; } /** * @dev Distribute funds to the winner, platform, and partners. * * @param _weiWin Funds for distribution. * @param _game A number of the game. * @param _matched A number of the player matches. * @param _player Player address. * @param _bet Player bet. */ function distributeFunds( uint256 _weiWin, uint256 _game, uint8 _matched, address _player, bytes3 _bet ) internal { uint256 toOwner = _weiWin.mul(commission).div(100); uint256 toPartner = 0; address partner = referralSystem.getPartner(msg.sender); if (partner != 0x0) { toPartner = toOwner.div(100); partner.transfer(toPartner); emit RaisedByPartner( partner, _player, 0x01, _game, toPartner, now ); } _player.transfer(_weiWin - toOwner); bool result = address(dao) .call .gas(20000) .value(toOwner - toPartner)(bytes4(keccak256("acceptFunds()"))); if (!result) { revert(); } emit BetPaid( _player, _game, _matched, _bet, _weiWin, now ); if (_matched == 6) { emit Jackpot( _player, _game, _weiWin, now ); } } /** * @dev Make payments in calculated game. * * @param _game A number of the game. * @param _toProcess Amount of payments for the process. */ function makePayments(uint256 _game, uint256 _toProcess) public { require(gameIsCalculated(_game)); require(winners[_game].length != 0); require(betsPaymentsProgress[_game] < winners[_game].length); uint256 steps = _toProcess; if (betsPaymentsProgress[_game] + steps > winners[_game].length) { steps -= betsPaymentsProgress[_game] + steps - winners[_game].length; } uint256 weiWin = 0; uint256 to = betsPaymentsProgress[_game] + steps; for (uint256 i = betsPaymentsProgress[_game]; i < to; i++) { if (winners[_game][i].matches != 6) { uint256 weiByMatch = weiRaised[gamePlayed].mul(percents[winners[_game][i].matches]).div(100); weiWin = weiByMatch.div(gameStats[_game][winners[_game][i].matches]); } else { if (raisedJackpots[_game] == 0 && jackpot != 0) { raisedJackpots[_game] = jackpot; jackpot = 0; } weiWin = raisedJackpots[_game].div(gameStats[_game][winners[_game][i].matches]); } distributeFunds( weiWin, _game, winners[_game][i].matches, gameBets[game][winners[_game][i].betIndex].player, gameBets[game][winners[_game][i].betIndex].bet ); } betsPaymentsProgress[_game] = i; } /** * @dev Get Grand jackpot start block. * * @param _game A number of the game. */ function getChampionStartBlock(uint256 _game) public view returns (uint256) { return championGameStartBlock[_game]; } /** * @dev Get players in Grand jackpot. * * @param _game A number of the game. */ function getChampionPlayersCountByGame(uint256 _game) public view returns (uint256) { return gamePlayers[_game].length; } /** * @dev Check if is number at the end of the game hash. * * @param _game A number of the game. */ function isNumber(uint256 _game) private view returns (bool) { bytes32 hash = blockhash(_game); require(hash != 0x0); byte b = byte(hash[31]); uint hi = uint8(b) / 16; uint lo = uint8(b) - 16 * uint8(hi); if (lo <= 9) { return true; } return false; } /** * @dev Get Grand jackpot interval. */ function getChampionCurrentInterval() public view returns (uint256) { if (leapYearStep != 4) { return CHAMPION_GAME_INTERVAL_ONE; } return CHAMPION_GAME_INTERVAL_TWO; } /** * @dev Get target Grand jackpot date. */ function targetChampionDate() public view returns (uint256) { return championGameStartedAt + getChampionCurrentInterval(); } /** * @dev Change step. */ function changeChampionStep() internal { uint256 interval = getChampionCurrentInterval(); championGameStartedAt += interval; if (leapYearStep == 4) { leapYearStep = 1; } else { leapYearStep += 1; } } /** * @dev Starts Grand jackpot game. */ function startChampionGame() public { require(currentGameBlockNumber == 0); require(targetChampionDate() <= now); currentGameBlockNumber = game; game = block.number; championGameStartBlock[currentGameBlockNumber] = block.number + startBlockInterval; emit ChampionGameStarted(currentGameBlockNumber, now); changeChampionStep(); } /** * @dev Finish Grand jackpot game. */ function finishChampionGame() public { require(currentGameBlockNumber != 0); uint8 steps = getCurrentGameSteps(); uint256 startBlock = getChampionStartBlock(currentGameBlockNumber); require(startBlock + steps < block.number); if (gamePlayers[currentGameBlockNumber].length != 0) { uint256 lMin = 0; uint256 lMax = 0; uint256 rMin = 0; uint256 rMax = 0; (lMin, lMax, rMin, rMax) = processSteps(currentGameBlockNumber, steps); address winner = gamePlayers[currentGameBlockNumber][rMax]; uint256 toOwner = jackpot.mul(commission).div(100); uint256 jp = jackpot - toOwner; emit ChampionWinner( winner, currentGameBlockNumber, rMax, jackpot, now ); winner.transfer(jp); uint256 toPartner = 0; address partner = referralSystem.getPartner(winner); if (partner != 0x0) { toPartner = toOwner.mul(1).div(100); partner.transfer(toPartner); emit RaisedByPartner( partner, winner, 0x01, currentGameBlockNumber, toPartner, now ); } bool result = address(dao) .call .gas(20000) .value(toOwner - toPartner)(bytes4(keccak256("acceptFunds()"))); if (!result) { revert(); } jackpot = 0; } currentGameBlockNumber = 0; } /** * @dev Get steps in this Grand jackpot game. */ function getCurrentGameSteps() public view returns (uint8) { return uint8(getStepsCount(currentGameBlockNumber)); } /** * @dev Calculate game steps. * * @param _game A number of the game. */ function getStepsCount(uint256 _game) public view returns (uint256 y) { uint256 x = getChampionPlayersCountByGame(_game); assembly { let arg := x x := sub(x,1) x := or(x, div(x, 0x02)) x := or(x, div(x, 0x04)) x := or(x, div(x, 0x10)) x := or(x, div(x, 0x100)) x := or(x, div(x, 0x10000)) x := or(x, div(x, 0x100000000)) x := or(x, div(x, 0x10000000000000000)) x := or(x, div(x, 0x100000000000000000000000000000000)) x := add(x, 1) let m := mload(0x40) mstore(m, 0xf8f9cbfae6cc78fbefe7cdc3a1793dfcf4f0e8bbd8cec470b6a28a7a5a3e1efd) mstore(add(m,0x20), 0xf5ecf1b3e9debc68e1d9cfabc5997135bfb7a7a3938b7b606b5b4b3f2f1f0ffe) mstore(add(m,0x40), 0xf6e4ed9ff2d6b458eadcdf97bd91692de2d4da8fd2d0ac50c6ae9a8272523616) mstore(add(m,0x60), 0xc8c0b887b0a8a4489c948c7f847c6125746c645c544c444038302820181008ff) mstore(add(m,0x80), 0xf7cae577eec2a03cf3bad76fb589591debb2dd67e0aa9834bea6925f6a4a2e0e) mstore(add(m,0xa0), 0xe39ed557db96902cd38ed14fad815115c786af479b7e83247363534337271707) mstore(add(m,0xc0), 0xc976c13bb96e881cb166a933a55e490d9d56952b8d4e801485467d2362422606) mstore(add(m,0xe0), 0x753a6d1b65325d0c552a4d1345224105391a310b29122104190a110309020100) mstore(0x40, add(m, 0x100)) let value := 0x818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff let shift := 0x100000000000000000000000000000000000000000000000000000000000000 let a := div(mul(x, value), shift) y := div(mload(add(m,sub(255,a))), shift) y := add(y, mul(256, gt(arg, 0x8000000000000000000000000000000000000000000000000000000000000000))) } } /** * @dev Refill the Jackpot. */ function refillTheJackpot() public payable { require(msg.value > 0); jackpot += msg.value; } /** * @dev Get Grand jackpot game rules. * * @param _game A number of the game. */ function getChampionGameRules(uint256 _game) public view returns (uint8 left, uint8 right) { if (isNumber(_game)) { left = NUMBER; right = STRING; } else { left = STRING; right = NUMBER; } return (left, right); } /** * @dev Process Grand jackpot steps. * * @param _gameBlock A number of the game. * @param _step Step to which needed calculation. */ function processSteps(uint256 _gameBlock, uint8 _step) public view returns ( uint256 lMin, uint256 lMax, uint256 rMin, uint256 rMax ) { require(_gameBlock != 0); lMin = 0; lMax = 0; rMin = 0; rMax = gamePlayers[_gameBlock].length - 1; if (rMax == 0) { return (lMin, lMax, rMin, rMax); } if (gamePlayers[_gameBlock].length == 2) { rMin = rMax; } else if (isEvenNumber(rMax)) { lMax = rMax / 2; rMin = rMax / 2 + 1; } else { lMax = rMax / 2; rMin = rMax / 2 + 1; } if (_step == 0) { return (lMin, lMax, rMin, rMax); } uint256 startBlock = getChampionStartBlock(_gameBlock); require((startBlock + _step) < block.number); uint8 left = 0; uint8 right = 0; (left, right) = getChampionGameRules(startBlock); for (uint8 i = 1; i <= 35; i++) { if (lMin == lMax && lMin == rMin && lMin == rMax) { break; } bool isNumberRes = isNumber(startBlock + i); if ((isNumberRes && left == NUMBER) || (!isNumberRes && left == STRING) ) { if (lMin == lMax) { rMin = lMin; rMax = lMax; break; } rMax = lMax; } else if (isNumberRes && right == NUMBER || (!isNumberRes && right == STRING) ) { if (rMin == rMax) { lMin = rMin; lMax = rMax; break; } lMin = rMin; } if (rMax - lMin != 1) { lMax = lMin + (rMax - lMin) / 2; rMin = lMin + (rMax - lMin) / 2 + 1; } else { lMax = lMin; rMin = rMax; } if (i == _step) { break; } } return (lMin, lMax, rMin, rMax); } /** * @dev Check if is even number. * * @param _v1 Number. */ function isEvenNumber(uint _v1) internal pure returns (bool) { uint v1u = _v1 * 100; uint v2 = 2; uint vuResult = v1u / v2; uint vResult = _v1 / v2; if (vuResult != vResult * 100) { return false; } return true; } }
* @dev Status of the played game (true if the game is in the process, false if the game is finished)./
bool public gamePlayedStatus = false;
12,946,972
[ 1, 1482, 434, 326, 6599, 329, 7920, 261, 3767, 309, 326, 7920, 353, 316, 326, 1207, 16, 629, 309, 326, 7920, 353, 6708, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1426, 1071, 7920, 11765, 329, 1482, 273, 629, 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 ]